将动态类型传递给通用模板

Pass dynamically type to generic template

我在 C# 中遇到反射问题。我需要构造一个通用方法,通过反射动态实例化 class 类型。我尝试的是以下内容。

Type myClass = Type.GetType(deviceBehavior.@class);
Type myInterfaceClass = myClass.GetInterface(deviceBehavior.@interface);

if (typeof (AnotherInterface).IsAssignableFrom(interfaceClass))
{
    CreateManager<interfaceClass>(serviceProvider, deviceCapability);
}

我的CreateManager方法如下:

private void CreateManager<T>(ServiceProvider serviceProvider, DeviceCapability deviceCapability)
{
    T instanceToCreate = CreateClass<T>(serviceProvider, deviceCapability);
    //Code to instantiate my class
}

问题是我无法调用

CreateManager(serviceProvider, deviceCapability);

如何将接口传递给我的泛型类型?我搜索了一下,没有找到我能看明白的东西。即

Calling a static method on a generic type parameter

Pass An Instantiated System.Type as a Type Parameter for a Generic Class

假设 CreateManager<T> 是类型 Foo:

的方法
public class Foo
{
    private void CreateManager<T>(ServiceProvider serviceProvider,
                                  DeviceCapability deviceCapability)
    {
    }
}

为了动态调用泛型方法,您需要先获取 MethodInfo,然后使用您要传递的实际类型调用 MakeGenericMethod(我选择 string 例如)

var foo = new Foo();
var createManagerMethod = foo.GetType()
                             .GetMethod("CreateManager", 
                                         BindingFlags.Instance | BindingFlags.NonPublic);

var method = createManagerMethod.MakeGenericMethod(typeof(string));
method.Invoke(foo, new object[] { new ServiceProvider(), new DeviceCapability() });

最后,使用正确的对象实例和参数调用 Invoke

我不明白,为什么您需要对此进行反思。你可以像下面那样做

public interface IYourInterface //Give it a good name
{
    void Instantiate(ServiceProvider serviceProvider, DeviceCapability deviceCapability);
}

public class YourClass : IYourInterface
{
    public YourClass() 
    {
        // do something if you want
    }

    public void Instantiate (ServiceProvider serviceProvider, DeviceCapability deviceCapability)
    {
       // what ever needs to be done here
    }
}

private void CreateManager<T>(ServiceProvider serviceProvider, DeviceCapability deviceCapability) 
    where T : IYourInterface, new()
{
    var instance = new T();
    instance.Instantiate(serviceProvider, deviceCapability);
}

/*
   Usage
*/

    CreateManager<YourClass>(serviceProvider, deviceCapability);