C# 将基类转换为派生类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12565736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert base class to derived class
提问by ARW
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:
这似乎不应该工作(对象被实例化为新基,因此不应为派生类的额外成员分配内存)但 C# 似乎允许我这样做:
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;
}
采纳答案by Tim S.
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.
不,没有像您说的那样转换类的内置方法。最简单的方法是按照您的建议进行操作:创建一个DerivedClass(BaseClass)构造函数。其他选项基本上会自动将属性从基础复制到派生实例,例如使用反射。
The code you posted using aswill compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClasswill evaluate to null, since it's not an instance of DerivedClass.
你发布的代码as会编译,我相信你已经看到了,但是当你运行它时会抛出一个空引用异常,因为myBaseObject as DerivedClass它将评估为null,因为它不是DerivedClass.
回答by Erix
No, there is no built in conversion for this. You'll need to create a constructor, like you mentioned, or some other conversion method.
不,没有为此内置转换。您需要创建一个构造函数,就像您提到的那样,或其他一些转换方法。
Also, since BaseClass is not a DerivedClass, myDerivedObject will be null, andd the last line above will throw a null ref exception.
此外,由于 BaseClass 不是 DerivedClass,因此 myDerivedObject 将为 null,并且上面的最后一行将抛出 null ref 异常。
回答by Jan P.
No it is not possible. The only way that is possible is
不,这是不可能的。唯一可能的方法是
static void Main(string[] args)
{
BaseClass myBaseObject = new DerivedClass();
DerivedClass myDerivedObject = myBaseObject as DerivedClass;
myDerivedObject.MyDerivedProperty = true;
}
回答by Matthias Meid
You can implement the conversion yourself, but I would not recommend that. Take a look at the Decorator Patternif you want to do this in order to extend the functionality of an existing object.
您可以自己实现转换,但我不建议这样做。如果您想这样做以扩展现有对象的功能,请查看装饰器模式。
回答by Mahmoodvcs
That's not possible. but you can use an Object Mapper like AutoMapper
那是不可能的。但是你可以使用像AutoMapper这样的对象映射器
Example:
例子:
class A
{
public int IntProp { get; set; }
}
class B
{
public int IntProp { get; set; }
public string StrProp { get; set; }
}
In global.asax or application startup:
在 global.asax 或应用程序启动中:
AutoMapper.Mapper.CreateMap<A, B>();
Usage:
用法:
var b = AutoMapper.Mapper.Map<B>(a);
It's easily configurable via a fluent API.
它可以通过流畅的 API 轻松配置。
回答by meffect
I have found one solution to this, not saying it's the best one, but it feels clean to me and doesn't require any major changes to my code. My code looked similar to yours until I realized it didn't work.
我找到了一种解决方案,并不是说它是最好的解决方案,但我觉得它很干净,不需要对我的代码进行任何重大更改。我的代码看起来和你的很相似,直到我意识到它不起作用。
My Base Class
我的基类
public class MyBaseClass
{
public string BaseProperty1 { get; set; }
public string BaseProperty2 { get; set; }
public string BaseProperty3 { get; set; }
public string BaseProperty4 { get; set; }
public string BaseProperty5 { get; set; }
}
My Derived Class
我的派生类
public class MyDerivedClass : MyBaseClass
{
public string DerivedProperty1 { get; set; }
public string DerivedProperty2 { get; set; }
public string DerivedProperty3 { get; set; }
}
Previous method to get a populated base class
先前获取填充基类的方法
public MyBaseClass GetPopulatedBaseClass()
{
var myBaseClass = new MyBaseClass();
myBaseClass.BaseProperty1 = "Something"
myBaseClass.BaseProperty2 = "Something else"
myBaseClass.BaseProperty3 = "Something more"
//etc...
return myBaseClass;
}
Before I was trying this, which gave me a unable to cast error
在我尝试这个之前,这让我无法投射错误
public MyDerivedClass GetPopulatedDerivedClass()
{
var newDerivedClass = (MyDerivedClass)GetPopulatedBaseClass();
newDerivedClass.UniqueProperty1 = "Some One";
newDerivedClass.UniqueProperty2 = "Some Thing";
newDerivedClass.UniqueProperty3 = "Some Thing Else";
return newDerivedClass;
}
I changed my code as follows bellow and it seems to work and makes more sense now:
我按如下方式更改了我的代码,它现在似乎可以工作并且更有意义:
Old
老的
public MyBaseClass GetPopulatedBaseClass()
{
var myBaseClass = new MyBaseClass();
myBaseClass.BaseProperty1 = "Something"
myBaseClass.BaseProperty2 = "Something else"
myBaseClass.BaseProperty3 = "Something more"
//etc...
return myBaseClass;
}
New
新的
public void FillBaseClass(MyBaseClass myBaseClass)
{
myBaseClass.BaseProperty1 = "Something"
myBaseClass.BaseProperty2 = "Something else"
myBaseClass.BaseProperty3 = "Something more"
//etc...
}
Old
老的
public MyDerivedClass GetPopulatedDerivedClass()
{
var newDerivedClass = (MyDerivedClass)GetPopulatedBaseClass();
newDerivedClass.UniqueProperty1 = "Some One";
newDerivedClass.UniqueProperty2 = "Some Thing";
newDerivedClass.UniqueProperty3 = "Some Thing Else";
return newDerivedClass;
}
New
新的
public MyDerivedClass GetPopulatedDerivedClass()
{
var newDerivedClass = new MyDerivedClass();
FillBaseClass(newDerivedClass);
newDerivedClass.UniqueProperty1 = "Some One";
newDerivedClass.UniqueProperty2 = "Some Thing";
newDerivedClass.UniqueProperty3 = "Some Thing Else";
return newDerivedClass;
}

