是否有可能分配一个基类对象派生类引用在C#中一个明确的类型转换? [英] Is it possible to assign a base class object to a derived class reference with an explicit typecast in C#?

查看:71
本文介绍了是否有可能分配一个基类对象派生类引用在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.

这篇关于是否有可能分配一个基类对象派生类引用在C#中一个明确的类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆