C# 泛型接口

4

我需要将一个通用类型参数传递给一个接口。我有一个包含类型名称的字符串。

我有类似于以下内容的代码:

string type = "ClassType";
Type t = Type.GetType("ClassType");

IProvider<t> provider = (IProvider<t>)someObject;

这个方法对我来说不起作用,正确的做法是什么?谢谢。

4个回答

8
你所尝试的在C#(和CLR)版本的泛型中实现并不是真正可能的。当指定泛型参数时,它必须是以下情况之一:
- 代码中的具体类型 - 另一个泛型参数
这些信息必须绑定在程序集的元数据中。无法以这种方式在元数据中表达字符串类型名称。
可以基于字符串名称在运行时绑定泛型,但这需要反射。

4

1

这里是一个使用反射加载泛型类型的示例。

using System;
namespace GenericCastRuntime
{
    class Program
    {
        static void Main(string[] args)
        {
            string type = "GenericCastRuntime.Program+Provider`1";
            Type t = Type.GetType(type);

            string genericType = "System.String";
            Type gt = Type.GetType(genericType);

            var objType = t.MakeGenericType(gt);
            var ci = objType.GetConstructor(Type.EmptyTypes);
            var obj = ci.Invoke(null);
            IProvider provider = obj as IProvider;
        }

        public class Provider<T> : IProvider<T>
        {
            public T Value { get; set; }

            object IProvider.Value
            {
                get { return this.Value; }
                set
                {
                    if (!(value is T)) throw new InvalidCastException();
                    this.Value = (T)value;
                }
            }

        }

        public interface IProvider { object Value { get; set; } }
        public interface IProvider<T> : IProvider { T Value { get; set; } }
    }
}

0

这是一个简单的例子:

    public static object DynamicallyCreateGeneric(Type GenericTypeSource, Type SpecificTypeSource)
    {
        System.Type SpecificType = 
            GenericTypeSource.MakeGenericType(
            new System.Type[] { SpecificTypeSource }
            );

        return Activator.CreateInstance(SpecificType);
    }

...然后,例如:

        string type = "System.String";
        Type t = Type.GetType(type);

        var DynamicallyCreatedGeneric = DynamicallyCreateGeneric(typeof(List<>), t);

        System.Diagnostics.Debugger.Break();

根据您的实现和口味进行调整。当然,这种方法并不理想。泛型最好的部分之一是类型编译器级别的类型安全性。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接