比较开放泛型参数和开放泛型接口类型

Compare open generic parameter with open generic interface type

是否可以(在 c# 中)比较一个开放的通用参数,例如T 在:

public void CompareMethod<T>() { ... }

使用开放通用接口的类型(或class)?
这是一个示例界面:

public interface IExample<T> { }

然后在方法内部以某种方式比较它们:

public void CompareMethod<T>()
{
    if (typeof(IExample<>) == typeof(T))
    {
        //execute
    }
}

if 函数体在调用如下方法时不会执行:

CompareMethod<IExample<object>>();

重要我事先不知道CompareMethod.

的开放泛型参数中会输入哪些封闭类型

您需要在 T 上调用 GetGenericTypeDefinition() 才能与 IExample<> 进行比较:

public void CompareMethod<T>()
{
    if (typeof(T).IsGenericType && 
        typeof(T).GetGenericTypeDefinition() == typeof(IExample<>)) {
    {
        //execute
    }
}