反射表单使用Generic界面创建实例

时间:2016-02-29 11:45:15

标签: c# generics

我的界面有一个通用的选择:

        public interface IMyInterface{
              void ok();
        }

        var maps = (from t in types
                    from i in t.GetInterfaces()
                    where typeof(IMyInterface).IsAssignableFrom(t) &&
                          !t.IsAbstract &&
                          !t.IsInterface
                    select (IMyInterface)Activator.CreateInstance(t)).ToArray();

但我将界面改为通用,

        public interface IMyInterface<T>{
              void ok<T>();
        }

        var maps = (from t in types 
                    from i in t.GetInterfaces()
                    where i.IsGenericType 
                        && i.GetGenericTypeDefinition() == typeof(IMyInterface<>)
                        && !t.IsAbstract
                        && !t.IsInterface
                        select ???????????????????????????????
                    ).ToArray();

但现在施法不起作用。

        select (IMyInterface<>)Activator.CreateInstance(t)).ToArray();

为施法提供构建错误。

1 个答案:

答案 0 :(得分:0)

IMyInterface<T> a IMyInterface<>,因此演员表无效。编译器只是保护您不会在运行时找到它,因为您可以永远在C#中具有类型GenericType<>的值 - 未实现的泛型类型仅用于反射。

请注意typeof(IMyInterface<>).IsAssignableFrom(typeof(IMyInterface<string>))如何返回false。这两种类型完全不同,只共享一个通用的通用定义,与List<int>相同,List<string>是两种不同的类型,只共享一个通用的通用定义。 C#泛型不是Java泛型。

您可以使用通用类型来包含List<string>List<int>,就像您可以用于IMyInterface<A>IMyInterface<B>的常用类型一样。要么确保所有内容都是通用的,要么使另一个非通用的接口和IMyInterface<T>实现。