传递动态类型

时间:2014-02-20 06:54:03

标签: c# reflection

我知道用反射传递动态类型但是具有以下类结构我有一点困难;我的调用类将实例化另一个类并在其基类上调用方法,将该方法传递给动态类型。

public class MainClass
{
    // var genericClass = new GenericClass();
    // genericClass.SomeMethod<T>();
    var myDynamicType = Type.GetType(FullyQualifiedNamespace + className);
    Activator.CreateInstance(myDynamicType);
}

public class GenericClass : GenericBase
{
}

public abstract class GenericBase
{
   private readonly List<IMyInterface> myList = new List<IMyInterface>();

   public void SomeMethod<T>() where T : IMyInterface, new ()
   {
       myList.Add(new T());
   }
} 

2 个答案:

答案 0 :(得分:1)

您可以使用SomeMethod<T>()更改SomeMethod(Type t)的方法签名。

public void SomeMethod(Type t)
    {
        if (t.GetInterfaces().Contains(typeof(IMyInterface)) && 
               t.GetConstructor(Type.EmptyTypes)!=null)
        {
            var obj=(IMyInterface)Activator.CreateInstance(t);
            myList.Add(obj);
        }
    }

答案 1 :(得分:0)

您有两种选择。第一种方法是将SomeMethod<T>方法修改为非泛型或添加非泛型过载:

public void SomeMethod(Type t) {
    var myInterface = (IMyInterface)Activator.CreateInstance(t);

    myList.Add(myInterface);
}

public void SomeMethod<T>() where T : IMyInterface, new ()
{
   SomeMethod(typeof(T));
}

然后打电话如下:

var myDynamicType = Type.GetType(FullyQualifiedNamespace + className);  //I assume this is the type that you want to use as the generic constraint 'T' of SomeMethod<T>

var genericClass = new GenericClass();
genericClass.SomeMethod(myDynamicType);

或者,您可以单独保留SomeMethod<T>方法并通过反射调用该方法:

var myDynamicType = Type.GetType(FullyQualifiedNamespace + className);  //I assume this is the type that you want to use as the generic constraint 'T' of SomeMethod<T>

var genericClass = new GenericClass();
var method = typeof(GenericClass).GetMethod("SomeMethod").MakeGenericMethod(myDynamicType);
method.Invoke(genericClass);