[英]Compare open generic parameter with open generic interface type
Is it possible (in c#
) to compare an open generic parameter eg T
in: 是否可以(在
c#
)比较开放的通用参数,例如T
in:
public void CompareMethod<T>() { ... }
with the type of an open generic interface (or class)? 开放的通用接口(或类)的类型?
Here is an example interface: 这是一个示例界面:
public interface IExample<T> { }
And then somehow inside the method compare them like this: 然后以某种方式在方法内部将它们进行如下比较:
public void CompareMethod<T>()
{
if (typeof(IExample<>) == typeof(T))
{
//execute
}
}
The if
body won't execute when called the method like this: 调用像这样的方法时,
if
主体将不会执行:
CompareMethod<IExample<object>>();
It is important that I don't know in advance what closed types will be entered in the open generic parameter of the CompareMethod
. 重要的是,我事先不知道在
CompareMethod
的open泛型参数中将输入哪些封闭类型。
You need to call GetGenericTypeDefinition()
on T
to be able to compare it with IExample<>
: 您需要在
T
上调用GetGenericTypeDefinition()
才能将其与IExample<>
进行比较:
public void CompareMethod<T>()
{
if (typeof(T).IsGenericType &&
typeof(T).GetGenericTypeDefinition() == typeof(IExample<>)) {
{
//execute
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.