是否可以(在c#中)比较一个开放的泛型参数,例如T:
public void CompareMethod<T>() { ... }使用开放的泛型接口(或类)的类型?
下面是一个示例接口:
public interface IExample<T> { }然后以某种方式在方法中像这样比较它们:
public void CompareMethod<T>()
{
if (typeof(IExample<>) == typeof(T))
{
//execute
}
}当调用这样的方法时,if主体将不会执行:
CompareMethod<IExample<object>>();重要的是,我不知道在CompareMethod的开放泛型参数中将输入哪些封闭类型。
发布于 2015-09-24 12:04:29
您需要在GetGenericTypeDefinition()上调用T,以便能够将其与IExample<>进行比较
public void CompareMethod<T>()
{
if (typeof(T).IsGenericType &&
typeof(T).GetGenericTypeDefinition() == typeof(IExample<>)) {
{
//execute
}
}https://stackoverflow.com/questions/32760640
复制相似问题