为什么我不能使用的界面与明确的运营商?我不、运营商、界面、明确

2023-09-02 01:37:34 作者:帝后

我只是想知道如果任何人知道你为什么不能使用接口与隐性或显性运营商的原因?

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"

谢谢

推荐答案

科10.9.3 C#的规范阐明这一点的。短版本是它不允许,使得用户可以确信当且仅当所述参考类型实际上实现该接口该引用类型和接口之间的转换成功,并且,当该转换发生,同样的对象实际上是被引用。

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.

用户自定义的转换不允许转换或接口类型的。特别是,该限制可确保没有用户定义的变换变换为的接口类型时发生的,并且转换到的接口型的成功仅当对象是转换实际上实现指定的接口类型的。

User-defined conversions are not allowed to convert from or to interface-types. In particular, this restriction ensures that no user-defined transformations occur when converting to an interface-type, and that a conversion to an interface-type succeeds only if the object being converted actually implements the specified interface-type.

 
精彩推荐
图片推荐