为什么不能从接口到类定义隐式转换运算符? [英] Why isn't it possible to define implicit cast operator from interface to class?

查看:120
本文介绍了为什么不能从接口到类定义隐式转换运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个界面

public interface ISomeControl
{
    Control MyControl { get; }
    ...
}

是否可以像这样定义smth :

Is it possible to define smth like this:

public static implicit operator Control(ISomeControl ctrl)
{
    return ctrl.MyControl;
}

或者说为什么我不能在C#中这样做?

Or rather why can't I do that in C#?

推荐答案

如果你有一个 Control 的子类怎么办,那个子类实现了 ISomeControl interface。

What if you had a subclass of Control, and that subclass implemented the ISomeControl interface.

class SomeControl : Control, ISomeControl {}

现在演员阵容不明确 - 内置向上播放和用户定义的转换。因此,您无法为接口提供用户定义的转换。

Now a cast would be ambiguous -- the built-in upcast, and your user-defined conversion. So you can't provide user-defined conversions for interfaces.

这篇关于为什么不能从接口到类定义隐式转换运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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