问题描述
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);
}
}
这是行不通的。为什么是不是允许的?结果
我的可以的潜在写逻辑必要为它是有意义的,特别是从碱转化为派生之一,当。
This won't work. why isn't it allowed?
I can potentially write the logic necessary for it to make sense, especially when converting from the base to the derived one.
编辑:改变了问题。
推荐答案
由于已经存在的隐式转换的标题从导出
到的BaseClass
,以及反之则没有任何意义。
Because there is already an implicit conversion from Derived
to BaseClass
, and the converse does not make any sense.
关于后者:如果你的基础
的对象,目的是要隐式转换为派生
- 为什么是他们不派生
放在首位对象
Regarding the latter: if your Base
objects are meant to be implicitly convertible to Derived
-- why aren't they Derived
objects in the first place?
从的:
隐式引用转换为:
- [。 ..]
- 从任意类类型S到任意类类型T,只要S是在T衍生
这表示有一个隐式转换派生
=> 基础
,因为大家都知道。
This says there's an implicit conversion Derived
=> Base
, as we all know.
显式引用转换为:
- [...]
- 从任何类类型S到任意类类型T,只要S是一个基类的T。
- [...]
这表示已经有一个明确的转换基本
=> 导出
(这是什么让你尝试在运行时向下转换)。
This says there's already an explicit conversion Base
=> Derived
(which is what allows you to try downcasting at runtime).
C#只允许某些用户定义的转换。
和本说,由于感兴趣的两次转换已经由语言定义的,你不能重新定义它们。
And this says that since the two conversions of interest are already defined by the language, you can't redefine them.
这篇关于为什么我不能写从基类的隐式操作员在C#中派生类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!