将基类转换为派生类 [英] Convert base class to derived class

查看:51
本文介绍了将基类转换为派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 C# 中将基类对象显式转换为其派生类之一?目前认为我必须为我的派生类创建一个构造函数,它接受一个基类对象作为参数并复制属性值.我不太喜欢这个主意,所以我想尽可能避免它.

Is it possible in C# to explicitly convert a base class object to one of it's derived classes? Currently thinking I have to create a constructor for my derived classes that accept a base class object as a parameter and copy over the property values. I don't really like this idea, so I'd like to avoid it if possible.

这似乎不应该工作(对象被实例化为新基,因此不应为派生类的额外成员分配内存)但 C# 似乎允许我这样做:

This doesn't seem like it should work (object is instantiated as new base, so memory shouldn't be allocated for extra members of the derived class) but C# seems to allow me to do it:

class BaseClass
{
  ... some stuff ...
}

class DerivedClass : BaseClass
{
    public bool MyDerivedProperty{ get; set; }
}


static void Main(string[] args)
{
    BaseClass myBaseObject = new BaseClass();
    DerivedClass myDerivedObject = myBaseObject as DerivedClass;

    myDerivedObject.MyDerivedProperty = true;
}

推荐答案

不,没有像您说的那样转换类的内置方法.最简单的方法是按照您的建议进行操作:创建一个 DerivedClass(BaseClass) 构造函数.其他选项基本上会自动将属性从基础复制到派生实例,例如使用反射.

No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass) constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.

您使用 as 发布的代码将被编译,我相信您已经看到了,但是当您运行它时会抛出一个空引用异常,因为 myBaseObject as DerivedClass 将评估为 null,因为它不是 DerivedClass 的实例.

The code you posted using as will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass will evaluate to null, since it's not an instance of DerivedClass.

这篇关于将基类转换为派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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