c# - 为什么我不能在 C# 中编写从基类到派生类的隐式运算符?

标签 c# operators

public class Derived : BaseClass
{
    public Derived(string name) : base(name) {}

    public static implicit operator BaseClass(Derived derived)
    {
        return new BaseClass(derived.ColorHex);
    }

    public static implicit operator Derived(BaseClass baseclass)
    {
        return new Derived(baseclass.name);
    }
}

这行不通。为什么不允许?
可以潜在地编写使其有意义的必要逻辑,尤其是在从基础转换为派生逻辑时。

编辑:更改了问题的标题

最佳答案

因为已经存在从DerivedBaseClass的隐式转换,反过来没有任何意义。

关于后者:如果您的 Base 对象可以隐式转换为 Derived - 为什么它们不是 Derived 对象第一名?

来自 standard 的强制性引述:

6.1.6 Implicit reference conversions

The implicit reference conversions are:

  • [...]
  • From any class-type S to any class-type T, provided S is derived from T.

这表示有一个隐式转换 Derived => Base,我们都知道。

6.2.4 Explicit reference conversions

The explicit reference conversions are:

  • [...]
  • From any class-type S to any class-type T, provided S is a base class of T.
  • [...]

这表示已经有一个显式转换 Base => Derived(这允许您在运行时尝试向下转型)。

6.4.1 Permitted user-defined conversions

C# permits only certain user-defined conversions to be declared. In particular, it is not possible to redefine an already existing implicit or explicit conversion.

这表示由于感兴趣的两个转换已经由语言定义,因此您不能重新定义它们。

关于c# - 为什么我不能在 C# 中编写从基类到派生类的隐式运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10853141/

相关文章:

MySql REGEXP 运算符

‘operator ’ 的 C++ 不明确重载

c# - 如何在 MySqlCommand 中包含 "declare"语法

c# - 隐藏在设计模式下使用它的页面中的母版页内容

C# 属性封装

c# - 当查询不为空时,自动映射器投影返回空列表

c - 乘法在 for 循环中不能很好地工作

MySql XNOR 等效项

c# - ASP.NET Linkbutton 中的自定义数据属性

c++ - 在 C++ 中使用 "+"连接字符串