投父对象到子对象在C# [英] cast the Parent object to Child object in C#
问题描述
您好我想投的父对象到子对象在C#
Hi i want to cast the Parent object to Child object in 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
推荐答案
如果我理解你的我只是想自动填补这些意见正确,你想创建一个与家长的值填充一个新的子对象,与新的属性的默认值。要做到这一点的最佳方式是创建一个构造函数,复制值:
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:
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;
}
}
现在你可以使用LINQ,像上述的答案,创建一个子从每个家长:
Now you can use LINQ, like the answers above, to create a Child out of each Parent:
List<Child> lstChild = lstParent.Select(parent => new Child(parent)).ToList();
请注意,这是非常相似的@ daryal的答案,但包装了家长对孩子的复制逻辑在构造函数中,而不是外面有它在新的儿童()
调用。
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.
这篇关于投父对象到子对象在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!