在 C# 中将父对象强制转换为子对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9885644/
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
cast the Parent object to Child object in C#
提问by Adnan Zameer
Hi i want to cast the Parent object to Child object in C#
嗨,我想在 C# 中将父对象转换为子对象
public class Parent
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string City {get; set;}
}
public class Child : Parent
{
public string PhoneNumber {get; set;}
public string MobileNumber {get; set;}
}
now the scenario is is a list of parent object and i want to generate list of child object so that i can have extended information
现在场景是父对象列表,我想生成子对象列表,以便我可以拥有扩展信息
List<Parent> lstParent;
List<Child> lstChild = new List<Child>();
foreach(var obj in lstParent)
{
lstChild.add((Child)obj);
}
as child class inherited parent class so the child class already have the parent class member i just want to fill them automatically so that i can populate datamember of child class
因为子类继承了父类所以子类已经有了父类成员我只想自动填充它们以便我可以填充子类的数据成员
采纳答案by Avner Shahar-Kashtan
If I understand your "I just want to fill them automatically" comment correctly, you want to create a new Child object that's populated with the values of the Parent, with default values for the new properties. Best way to do that is to create a constructor that copies the values:
如果我正确理解了您的“我只是想自动填充它们”的注释,那么您想创建一个新的 Child 对象,该对象填充了 Parent 的值,并使用新属性的默认值。最好的方法是创建一个复制值的构造函数:
public class Parent
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string City {get; set;}
}
public class Child : Parent
{
public string PhoneNumber {get; set;}
public string MobileNumber {get; set;}
public Child (Parent parentToCopy)
{
this.FirstName = parentToCopy.FirstName;
this.LastName = parentToCopy.LastName;
this.City = parentToCopy.City;
this.PhoneNumber = string.Empty; // Or any other default.
this.MobileNumber = string.Empty;
}
}
Now you can use LINQ, like the answers above, to create a Child out of each Parent:
现在您可以像上面的答案一样使用 LINQ 从每个父级中创建一个子级:
List<Child> lstChild = lstParent.Select(parent => new Child(parent)).ToList();
Note that this is very similar to @daryal's answer, but wraps the parent-to-child copying logic inside the constructor, rather than having it outside in the new Child()call.
请注意,这与@daryal 的答案非常相似,但将父到子复制逻辑包装在构造函数中,而不是将其放在new Child()调用之外。
回答by Marc Gravell
var lstChild = lstParent.Cast<Child>().ToList();
or
或者
var lstChild = lstParent.ConvertAll(x=>(Child)x);
Both of these, however, assume that the Parentlist actually contains Childinstances. You can't change the actual type of an object.
然而,这两者都假设Parent列表实际上包含Child实例。您无法更改对象的实际类型。
回答by daryal
You may use reflection as well, but this is simpler for your case.
您也可以使用反射,但这对您的情况来说更简单。
foreach(var obj in lstParent)
{
Child child = new Child(){ FirstName = obj.FirstName, LastName=obj.LastName, City = obj.City};
child.MobileNumber = "some mobile number";
child.PhoneNumber = "some phone number";
lstChild.Add((Child)obj);
}
回答by Aleksey Timkov
I do so (this is just an example):
我这样做(这只是一个例子):
using System.Reflection;
public class DefaultObject
{
...
}
public class ExtendedObject : DefaultObject
{
....
public DefaultObject Parent { get; set; }
public ExtendedObject() {}
public ExtendedObject(DefaultObject parent)
{
Parent = parent;
foreach (PropertyInfo prop in parent.GetType().GetProperties())
GetType().GetProperty(prop.Name).SetValue(this, prop.GetValue(parent, null), null);
}
}
Using:
使用:
DefaultObject default = new DefaultObject { /* propery initialization */ };
ExtendedObject extended = new ExtendedObject(default); // now all properties of extended are initialized by values of default properties.
MessageBox.Show(extended.Parent.ToString()); // now you can get reference to parent object
回答by sayyed mohsen zahraee
I did like this:
我是这样的:
class Parent
{
...
}
class Child :Parent
{
...
public Child(Parent p)
{
foreach (FieldInfo prop in p.GetType().GetFields())
GetType().GetField(prop.Name).SetValue(this, prop.GetValue( p));
foreach (PropertyInfo prop in p.GetType().GetProperties())
GetType().GetProperty(prop.Name).SetValue(this, prop.GetValue( p, null), null);
}
}
回答by LawMan
This is what I came up with form my solution.
这就是我从我的解决方案中提出的。
public static void ShallowConvert<T, U>(this T parent, U child)
{
foreach (PropertyInfo property in parent.GetType().GetProperties())
{
if (property.CanWrite)
{
property.SetValue(child, property.GetValue(parent, null), null);
}
}
}
回答by Michael Johnston
Another way to approach this solution is to have the Parentcontrol the copy logic and Childwill pass the copy source into the baseconstructor.
解决此解决方案的另一种方法是Parent控制复制逻辑并将Child复制源传递给base构造函数。
e.g. iterating on Avner's solution
例如迭代 Avner 的解决方案
public class Parent
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string City {get; set;}
public Parent()
{
}
public Parent(Parent copyFrom)
{
this.FirstName = copyFrom.FirstName;
this.LastName = copyFrom.LastName;
this.City = copyFrom.City;
}
}
public class Child : Parent
{
public string PhoneNumber {get; set;}
public string MobileNumber {get; set;}
public Child (Parent parentToCopy) : base(parentToCopy)
{
}
}

