Why can#39;t I use interface with explicit operator?(为什么我不能将接口与显式运算符一起使用?)
问题描述
我只是想知道是否有人知道为什么不允许您使用带有隐式或显式运算符的接口?
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"
谢谢,
推荐答案
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.
用户定义的转换不允许从interface-types转换.特别是,此限制可确保在转换为 interface-type 时不会发生用户定义的转换,并且只有当对象为转换后实际上实现了指定的interface-type.
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#保存对话框的文件路径 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
