有没有办法确定 C# 4.0 中接口/委托的方差?
现在,我们在 C# 中的接口和委托上有了通用协变和逆变,我只是好奇如果给定一个 Type
,您可以计算出其通用参数的协变/逆变。我开始尝试编写自己的实现,它将查看给定类型的所有方法,并查看返回类型和/或参数是否与泛型参数中的类型匹配。问题是,即使我有这个:
public interface IFoo<T>
{
void DoSomething(T item);
}
使用我的逻辑,它看起来应该是逆变的,但由于我们实际上没有指定:
public interface IFoo<in T>
{
void DoSomething(T item);
}
(in 参数)它实际上并不是逆变的。这引出了我的问题:有没有办法确定通用参数的方差?
So now that we have generic Covariance and Contravariance on interfaces and delegates in C#, I was just curious if given a Type
, you can figure out the covariance/contravariance of its generic arguments. I started trying to write my own implementation, which would look through all of the methods on a given type and see if the return types and or arguments match the types in the generic arguments. The problem is that even if I have this:
public interface IFoo<T>
{
void DoSomething(T item);
}
using my logic, it LOOKS like it should be contravariant, but since we didn't actually specify:
public interface IFoo<in T>
{
void DoSomething(T item);
}
(the in parameter) it isn't actually contravariant. Which leads to my question: Is there a way to determine the variance of generic parameters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道你为什么想要这个,但你可以从类型外部的反射来看待它。以下是有关使用反射查看类型的通用参数的信息:
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
真的很有趣...感谢您提出这个问题并让我查找它。
I don't know why you would want this, BUT you can look at it with reflection from outside of the type. Here's information on looking at Generic Parameters for a type using reflection:
http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx
Specifically, the property Type.GenericParameterAttributes on the type you get back from a call to Type.GetGenericParameters will reveal the Co/Contravariance properties of the generic argument... it's a bitwise enum that will reveal the combination of this information:
http://msdn.microsoft.com/en-us/library/system.reflection.genericparameterattributes.aspx
Really interesting... thanks for asking this and making me look it up.