是否有可能分配一个基类对象派生类引用在C#中一个明确的类型转换?

是否有可能分配一个基类对象派生类引用在C#中一个明确的类型转换?

问题描述:

是否有可能一个基类对象分配给派生类的引用在C#?

Is it possible to assign a base class object to a derived class reference with an explicit typecast in C#?.

我已经尝试过了,它会创建一个运行时错误。

I have tried it and it creates a run-time error.

没有。派生类的引用必须实际指的是派生类(或空)的一个实例。否则你将如何指望它表现?

No. A reference to a derived class must actually refer to an instance of the derived class (or null). Otherwise how would you expect it to behave?

例如:

object o = new object();
string s = (string) o;
int i = s.Length; // What can this sensibly do?

如果您希望能够到基本类型的实例转换为派生类型,我建议你写来建立一个适当的派生类型实例的方法。还是看你的继承树再次尝试重新设计,使您不必这样做摆在首位。

If you want to be able to convert an instance of the base type to the derived type, I suggest you write a method to create an appropriate derived type instance. Or look at your inheritance tree again and try to redesign so that you don't need to do this in the first place.