无法将类型'BaseClass'隐式转换为'DerivedClass'
问题描述:
亲爱的开发者,
请注意以下C#代码。
Hi dear developers,
Please observe the following C# code once.
class BaseClass
{
public void Method1(){}
}
class DerivedClass : BaseClass
{
public void Method2(){}
}
class Program
{
static void Main()
{
BaseClass bc = new BaseClass();
DerivedClass dc = new DerivedClass();
BaseClass bcd = new DerivedClass();
DerivedClass dcb = new BaseClass(); /*compile time error. Cannot implicitly convert type 'BaseClass' to 'DerivedClass'. An explicit conversion exists (are you missing a cast?)*/
}
}
当我将基类对象分配给派生类变量编译器时抛出错误无法将类型'BaseClass'隐式转换为'DerivedClass'。但是,当我将派生类对象分配给基类对象时,我没有收到错误。
你能否澄清一下为什么会发生这种情况。
When i am assigning the base class object to the derived class variable compiler throwing the error Cannot implicitly convert type 'BaseClass' to 'DerivedClass' . But, i am not getting the error when i am assigning the derived class object to the base class object.
Can you please clarify me why it is happening.
答
您无法自动将基类实例转换为派生类实例:它将涉及系统发明数据。你可以,如果你创建一个特定的强制转换操作符,因为你可以自己填写缺失的信息,但我真的不推荐它。
想想关于它:橙子是一种水果,但不是所有水果都是橙子 - 有些是苹果。
如果你创建一个水果的实例,它不是橙色或苹果 - 它是一个通用的水果,这可能不存在。
这就是为什么你经常看到人们创建基类为abstract
所以你甚至无法创建它们的实例。
You cannot automatically convert a base class instance into a derived class instance: it would involve the system "inventing" data. You can, if you create a specific cast operator because you can "fill in" the missing infor yourself, but I really don't recommend it at all.
Think about it: an Orange is a Fruit, but not all Fruits are Oranges - some are Apples.
If you create an instance of a Fruit, it is not an Orange or an Apple - it's a generic Fruit, which probably doesn't exist.
This is why you often see people create base classes asabstract
so that you cannot even create an instance of them.