[英]Reflection form create instance with Generic interface
I have a generic selection for my interface like this: 我对接口的选择如下:
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();
But I changed my interface to generic, 但是我将界面更改为通用,
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();
but now the casting is not working. 但现在投放失败。
select (IMyInterface<>)Activator.CreateInstance(t)).ToArray();
Gives build error for casting. 给出投放投放时的生成错误。
IMyInterface<T>
is not a IMyInterface<>
, therefore the cast is not valid. IMyInterface<T>
不是 IMyInterface<>
,因此IMyInterface<>
无效。 The compiler just protects you from finding this at runtime, because you can never have a value of type GenericType<>
in C# - non-reified generic types are only used for reflection. 编译器只是保护您免于在运行时发现该错误,因为在C#中永远不会有
GenericType<>
类型的值-非修饰的泛型类型仅用于反射。
Note how typeof(IMyInterface<>).IsAssignableFrom(typeof(IMyInterface<string>))
returns false
. 请注意
typeof(IMyInterface<>).IsAssignableFrom(typeof(IMyInterface<string>))
返回false
。 The two types are completely different and only share a common generic definition, the same as List<int>
and List<string>
are two different types that only share a common generic definition. 这两种类型是完全不同的,并且仅共享一个通用的泛型定义,与
List<int>
和List<string>
是两个不同的类型,它们仅共享一个通用的泛型定义。 C# generics aren't Java generics. C#泛型不是Java泛型。
There is no common type you can use to encompass both List<string>
and List<int>
, just like there's not common type you can use for your IMyInterface<A>
and IMyInterface<B>
. 没有可以用于包含
List<string>
和List<int>
的通用类型,就像没有可以用于IMyInterface<A>
和IMyInterface<B>
通用类型一样。 Either make sure everything is properly generic, or make another interface that isn't generic and that IMyInterface<T>
implements. 确保所有内容都正确通用,或者确保创建另一个非通用且由
IMyInterface<T>
实现的IMyInterface<T>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.