C# - 将泛型接口转换为传递类型<t>的泛型类,该类在运行时确定

时间:2016-02-19 04:20:00

标签: c# generics

如何通过传递在运行时确定的Type?

来转换具有泛型接口的泛型类
public class SomeDataChanged
    {
        public string EventName { get; set; }
    }

public class MessageSub<T> where T : class
{
    public IMessageBus Bus { get; set; }
    public ISubscription<T> Sub { get; set; }
}

public interface IDataChangedService<T> where T : class
{
    MessageSub<T> ProcessData(string topic, string subscription);
}

public class DataChangedService<T> : IDisposable, IDataChangedService<T> where T : class
{
    public MessageSub<T> ProcessData(string topic, string subscription)
    {
        // Some code
    }

    // More code
}

我使用了反射,使用以下thread将在运行时确定的类型传递给泛型类。但是没有得到如何将它转换为另一种通用类型。

class Test
{
    static void Main()
    {
        string topic = "OrderChanged";
        string subscription = "MyUi";
        string typeName = "OrderDataChanged";
        Type T = Type.GetType(typeName);

        Type genericClass = typeof(DataChangedService<>);
        Type constructedClass = genericClass.MakeGenericType(T);

        //How to cast another generic interface to my constructed class?
        var obj = (IDataChangedService<T>)Activator.CreateInstance(constructedClass); 

        //Also how to return generic type object?
        MessageSub<T> msgSub = obj.ProcessData(topic, subscription);

        // and, then some code that use msgSub
    }
}

1 个答案:

答案 0 :(得分:3)

你不能IDataChangedService<T>TSystem.Type类型的运行时变量,而不是字符串typeName表示的编译时类型。要使用泛型参数,类型必须是编译时。

您需要引入一些非泛型类型才能使其发挥作用。

这样的事情:

public interface IMessageSub { }

public class MessageSub<T> : IMessageSub where T : class
{
    public IMessageBus Bus { get; set; }
    public ISubscription<T> Sub { get; set; }
}

public interface IDataChangedService
{
    IMessageSub ProcessData(string topic, string subscription);
}

public interface IDataChangedService<T> : IDataChangedService where T : class
{
    MessageSub<T> ProcessData(string topic, string subscription);
}

public class DataChangedService<T> : IDataChangedService<T> where T : class
{
    IMessageSub IDataChangedService.ProcessData(string topic, string subscription)
    {
        return this.ProcessData(topic, subscription);
    }

    public MessageSub<T> ProcessData(string topic, string subscription)
    {
        // Some code
    }

    // More code
}

然后你可以这样做:

var obj = (IDataChangedService)Activator.CreateInstance(constructedClass);

obj.ProcessData(topic, subscription);