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

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

问题描述

是否有可能在C#中的基类对象显式转换为它的一个派生类?目前想我必须创建一个构造函数接受一个基类对象作为参数并复制的属性值我的派生类。我真的不喜欢这个想法,所以我想如果可能的话,以避免它。

这似乎并不像它应该工作(对象实例化新基地,使内存不应该被分配给派生类的额外的成员),但C#似乎让我做到这一点:

 类的BaseClass
{
  ......一些东西...
}类DerivedClass:BaseClass的
{
    公共BOOL MyDerivedProperty {搞定;组; }
}
静态无效的主要(字串[] args)
{
    BaseClass的myBaseObject =新的BaseClass();
    DerivedClass myDerivedObject = myBaseObject作为DerivedClass;    myDerivedObject.MyDerivedProperty = TRUE;
}


解决方案

没有,还有像你说的转换类没有内置的方式。要做到这一点最简单的方法是做你的建议:创建一个 DerivedClass(BaseClass的)构造函数。其他选项将基本上出来的属性复制从基础自动化到派生的实例,例如,使用反射。

您发布使用code 将编译,因为我相信你所看到的,但是当你运行它会抛出一个空引用异常,因为 myBaseObject作为DerivedClass 将评估为,因为它不是一个实例 DerivedClass

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.

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;
}

解决方案

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.

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天全站免登陆