开发者

Class<T,C> and Activator.CreateInstance

开发者 https://www.devze.com 2023-04-07 15:35 出处:网络
Here is some class: public class MyClass<T, C> : IMyClass where T : SomeTClass where C : SomeCClass

Here is some class:

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 instanciate 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 开发者_Python百科System.MissingMethodException(there is no no-arg constructor for this object)...

What is wrong with my code?


It sounds like typeOfSomeTClass or typeOfSomeCClass is a type that doesn't have a public parameterless constructor, as required by:

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

You could enforce that via a constraint:

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

in which case you can also then do:

this.t = new T();
this.c = new C();


MakeGenericType should use an array of Type in this context.

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

For example

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号