Class <T, C> and Activator.CreateInstance

Here are a few classes:

public class MyClass<T, C> : IMyClass where T : SomeTClass where C : SomeCClass { private T t; private C c; public MyClass() { this.t= Activator.CreateInstance<T>(); this.c= Activator.CreateInstance<C>(); } } 

And I'm trying to create an object of this class by doing this:

  Type type = typeof(MyClass<,>).MakeGenericType(typeOfSomeTClass, typeOfSomeCClass); object instance = Activator.CreateInstance(type); 

And all I get is a System.MissingMethodException (there is no no-arg constructor for this object) ...

What is wrong with my code?

+6
source share
2 answers

It looks like typeOfSomeTClass or typeOfSomeCClass is a type that does not have an open constructor without parameters, as required:

 this.t = Activator.CreateInstance<T>(); this.c = Activator.CreateInstance<C>(); 

You can apply this through a restriction:

 where T : SomeTClass, new() where C : SomeCClass, new() 

in this case, you can also:

 this.t = new T(); this.c = new C(); 
+8
source

MakeGenericType should use an array of type in this context.

See http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx

for instance

Type type = typeof (LigneGrille <,>). MakeGenericType (new type [] {typeOfSomeTClass, typeOfSomeCClass});

0
source

Source: https://habr.com/ru/post/898129/


All Articles