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);
}
}
这行不通。为什么不允许?
我可以潜在地编写使其有意义的必要逻辑,尤其是在从基础转换为派生逻辑时。
编辑:更改了问题的标题
最佳答案
因为已经存在从Derived
到BaseClass
的隐式转换,反过来没有任何意义。
关于后者:如果您的 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/