BFr*_*ree 9 c# reflection covariance contravariance
所以现在我们在C#中的接口和委托上有通用的协方差和逆变,我只是好奇如果给出a Type
,你可以弄清楚它的泛型参数的协方差/逆变.我开始尝试编写自己的实现,它将查看给定类型的所有方法,并查看返回类型和/或参数是否与泛型参数中的类型匹配.问题是,即使我有这个:
public interface IFoo<T>
{
void DoSomething(T item);
}
Run Code Online (Sandbox Code Playgroud)
使用我的逻辑,它看起来应该是逆变,但因为我们没有实际指定:
public interface IFoo<in T>
{
void DoSomething(T item);
}
Run Code Online (Sandbox Code Playgroud)
(in参数)它实际上不是逆变的.这引出了我的问题:有没有办法确定通用参数的方差?
我不知道为什么你会想要这个,但是你可以用类型外的反射来看它.以下是使用反射查看类型的通用参数的信息:
http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx
具体来说,从调用Type.GetGenericParameters返回的类型上的属性Type.GenericParameterAttributes将显示泛型参数的Co/Contravariance属性...它是一个按位枚举,将揭示此信息的组合:
http://msdn.microsoft.com/en-us/library/system.reflection.genericparameterattributes.aspx
非常有趣...感谢您提出这个并让我查看它.