为什么我不能将接口与显式运算符一起使用? [英] Why can't I use interface with explicit operator?

查看:30
本文介绍了为什么我不能将接口与显式运算符一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否有人知道为什么不允许您使用带有隐式或显式运算符的接口?

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.

这篇关于为什么我不能将接口与显式运算符一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆