为什么我不能使用带有显式运算符的接口?
我只是想知道是否有人知道不允许您使用带有隐式或显式运算符的接口的原因?
例如,这会引发编译时错误:
public static explicit operator MyPlayer(IPlayer player)
{
...
}
“不允许用户定义的接口转换”
谢谢,
I'm just wondering if anyone knows the reason why you are not allowed to use interfaces with the implicit or explicit operators?
E.g. this raises compile time error:
public static explicit operator MyPlayer(IPlayer player)
{
...
}
"user-defined conversions to or from an interface are not allowed"
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C# 规范第 10.9.3 节这个出来了。简而言之,这是不允许的,以便用户可以确定引用类型和接口之间的转换当且仅当引用类型实际实现该接口时才会成功,并且当该转换发生时实际上正在引用同一个对象。
定义引用类型之间的隐式或显式转换使用户期望引用会发生变化;毕竟,同一个引用不能同时是两种类型。另一方面,用户对于引用类型和接口类型之间的转换没有有相同的期望。
Section 10.9.3 of the C# spec spells this out. The short version is that it's disallowed so that the user can be certain that conversions between reference types and interfaces succeed if and only if the reference type actually implements that interface, and that when that conversion takes place that the same object is actually being referenced.
Defining an implicit or explicit conversion between reference types gives the user the expectation that there will be a change in reference; after all, the same reference cannot be both types. On the other hand, the user does not have the same expectation for conversions between reference types and interface types.