<分区>
我只是想知道是否有人知道为什么不允许您将接口(interface)与隐式或显式运算符一起使用的原因?
例如这会引发编译时错误:
public static explicit operator MyPlayer(IPlayer player)
{
...
}
“不允许用户定义的与接口(interface)之间的转换”
谢谢,
<分区>
我只是想知道是否有人知道为什么不允许您将接口(interface)与隐式或显式运算符一起使用的原因?
例如这会引发编译时错误:
public static explicit operator MyPlayer(IPlayer player)
{
...
}
“不允许用户定义的与接口(interface)之间的转换”
谢谢,
最佳答案
Section 10.9.3 of the C# spec说明了这一点。简而言之,它是不允许的,因此用户可以确定当且仅当引用类型实际实现了该接口(interface)时,引用类型和接口(interface)之间的转换才会成功,并且当该转换发生时,实际上正在引用同一对象。
在引用类型之间定义一个隐式或显式转换,让用户期望引用会发生变化;毕竟,同一个引用不能是两种类型。另一方面,用户不对引用类型和接口(interface)类型之间的转换有相同的期望。
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.
关于c# - 为什么我不能使用带有显式运算符的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2433204/