为什么我不能将接口与显式运算符一起使用?

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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)