在 C# 中将父对象强制转换为子对象 [英] cast the Parent object to Child object in C#
问题描述
我想在 C# 中将父对象转换为子对象
公共类父级{公共字符串名字{get;放;}公共字符串姓氏 {get;放;}公共字符串城市{get;放;}}公共类孩子:父母{公共字符串电话号码 {get;放;}公共字符串 MobileNumber {get;放;}}
现在的场景是父对象的列表,我想生成子对象的列表,以便我可以拥有扩展信息
ListlstParent;列表<孩子>lstChild = new List();foreach(lstParent 中的 var obj){lstChild.add((Child)obj);}
作为子类继承父类所以子类已经有父类成员我只想自动填充它们以便我可以填充子类的数据成员
如果我正确理解您的我只是想自动填充它们"的评论,您想创建一个新的 Child 对象,该对象填充了 Parent 的值,新属性的默认值.最好的方法是创建一个复制值的构造函数:
公共类父级{公共字符串名字{get;放;}公共字符串姓氏 {get;放;}公共字符串城市{get;放;}}公共类孩子:父母{公共字符串电话号码 {get;放;}公共字符串 MobileNumber {get;放;}公共孩子(父母 parentToCopy){this.FirstName = parentToCopy.FirstName;this.LastName = parentToCopy.LastName;this.City = parentToCopy.City;this.PhoneNumber = string.Empty;//或任何其他默认值.this.MobileNumber = string.Empty;}}
现在您可以使用 LINQ,就像上面的答案一样,从每个父级中创建一个子级:
ListlstChild = lstParent.Select(parent => new Child(parent)).ToList();
请注意,这与@daryal 的答案非常相似,但将父到子复制逻辑包装在构造函数中,而不是将其放在 new Child()
调用中.>
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;
}
}
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();
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屋!