一类参数C#方差注释,约束是值类型 [英] C# variance annotation of a type parameter, constrained to be value type

查看:168
本文介绍了一类参数C#方差注释,约束是值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在C#中可以添加方差注释类型参数约束为值类型:

 接口IFoo的<在T>其中T:结构
{
无效嘘(T X);
}



这是为什么由编译器允许的,如果方差标注在这样做完全没有意义情况如何?


解决方案

为什么这是由编译器允许,因为方差标注在这样做完全没有意义情况如何?




它是由编译器允许的,因为我从来没有认为,有人可能会尝试这样做,当我加入了方差规则的C#4.0编译器。



编译器警告和错误的功能的,并且为了使功能来实现,它必须在最低限度,是的在某些时候你想你的船编译器之前的。我没有这样做,因此从未有过的机会,甚至辩论是否应该有这样的情况的警告。



现在,你已经把它带到我的注意,问题是:的它是一个功能?如果编译器产生的这种情况下,一个警告(或错误)?



这是一个主观判断。我们会考虑一些事情:




  • 是那种事情的人可能会键入想它的代码做一些事情明智?人们希望不是;人们希望,谁知道有足够的了解类型系统进行接口变种开发商也知道,变化仅适用于引用类型。但也许有开发商在那里谁可能在想,它会工作键入此。它似乎并没有超出合理性至少。它没有明确做作。


  • 是代码的显然是错误的的?是的,它可能是。这似乎不太可能是有人故意想要写,看起来变型的接口,但实际上并非如此。




和这样上。



我得给它更多的思考,但乍一看它看起来像这实际上可能是一个体面的警告添加到编译器。我会与球队商量一下,我们会考虑将它添加到罗斯林版本。



感谢您的想法!


It is possible in C# to add variance annotation to type parameter, constrained to be value type:

interface IFoo<in T> where T : struct
{
  void Boo(T x);
}

Why is this allowed by compiler if variance annotation makes completely no sense in a such situation?

解决方案

Why this is allowed by compiler since variance annotation make completely no sense in a such situation?

It's allowed by the compiler because I never even considered that someone might try to do that when I added the variance rules to the C# 4.0 compiler.

Compiler warnings and errors are features, and in order for a feature to be implemented, it has to, at a bare minimum, be thought of at some point before you ship your compiler. I failed to do so, and therefore never had the opportunity to even debate whether there ought to be a warning for such a situation.

Now that you've brought it to my attention, the question is: should it be a feature? Should the compiler produce a warning (or error) for this case?

That's a judgment call. A number of things we'd consider are:

  • Is the code the sort of thing someone might type in thinking it does something sensible? One hopes not; one hopes that the developer who knows enough about the type system to make an interface variant also knows that variance only works on reference types. But maybe there are developers out there who might type this in thinking that it will work. It doesn't seem beyond plausibility at least. It's not clearly contrived.

  • Is the code clearly wrong? Yes, it probably is. It seems very unlikely that someone deliberately wants to write an interface that looks variant but in fact is not.

And so on.

I'll have to give it more thought, but at first glance it looks like this actually might be a decent warning to add to the compiler. I'll talk it over with the team and we'll consider adding it to the Roslyn version.

Thanks for the idea!

这篇关于一类参数C#方差注释,约束是值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆