是否可以使用显式类型转换将基类对象分配给派生类引用? [英] Is it possible to assign a base class object to a derived class reference with an explicit typecast?

查看:22
本文介绍了是否可以使用显式类型转换将基类对象分配给派生类引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 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.

推荐答案

没有.对派生类的引用必须实际引用派生类的实例(或 null).否则你会如何期望它的行为?

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.

这篇关于是否可以使用显式类型转换将基类对象分配给派生类引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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