elena1234

Reflection - get constructors and parameters

May 29th, 2021 (edited)
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.58 KB | None | 0 0
  1.  
  2. Type type = typeof(Car);
  3. ConstructorInfo[] allNonStaticCtors = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
  4.  
  5. foreach(var ctor in allNonStaticCtors)
  6. {
  7.    var parameters = ctor.GetParameters();
  8.  
  9.    foreach(var parameter in parameters)
  10.     {
  11.       Console.WriteLine($" - {paramter.ParameterType} {parameter.Name}"); // type and name
  12.     }
  13. }
  14.  
  15. //
  16. var constructor = type.GetConstructor  (BindingFlags.Instance | BindingFlags.NonPublic, new Type[] {typeof(int)}); // get ctor with int
  17. var car = (Ferrari)constructor.Invoke(new obj[] {123});
Add Comment
Please, Sign In to add comment