c# - 为什么我不能使用带有显式运算符的接口(interface)?

标签 c# .net type-conversion explicit

<分区>

我只是想知道是否有人知道为什么不允许您将接口(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/

相关文章:

c++ - std::function 隐式类型转换

c# - "Token?"的确切定义是什么

c# - LINQ:将 DataTable 转换为包含数组的用户定义类

.net - Double 和 Decimal 的精度(在 .NET 中)

c# - 使用带有 ISO-8859-1 编码的 XmlTextWriter 编写 XML 文件

variables - 如何在 julia 中将变量类型 "SentinelArrays"转换为 "Arrays{Float64,n}"

将阿拉伯数字(long long int)转换为C中的单词

IP 地址的 C# ComboBox

c# - 如何在 C# 中更快地缩略图

c# - 如何从 C# 代码调用 Azure 数据工厂管道?