在C#中将Parent对象强制转换为Child对象

Adn*_*eer 21 c# inheritance

您好我想在C#中将Parent对象强制转换为Child对象

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;}
}
Run Code Online (Sandbox Code Playgroud)

现在的场景是父对象的列表,我想生成子对象的列表,以便我可以有扩展的信息

List<Parent> lstParent;
List<Child> lstChild = new List<Child>();

foreach(var obj in lstParent)
{
    lstChild.add((Child)obj);
}
Run Code Online (Sandbox Code Playgroud)

作为子类继承父类,所以子类已经有父类成员我只想自动填充它们,以便我可以填充子类的datamember

小智 23

我这样做(这只是一个例子):

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用:

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
Run Code Online (Sandbox Code Playgroud)

  • 为什么不简单地“prop.SetValue(this, prop.GetValue(parent));”? (2认同)

Avn*_*tan 20

如果我理解你的"我只是想自动填充它们"注释正确,你想要创建一个新的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;
    } 
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以像上面的答案一样使用LINQ来创建每个Parent的Child:

List<Child> lstChild = lstParent.Select(parent => new Child(parent)).ToList();
Run Code Online (Sandbox Code Playgroud)

请注意,这与@daryal的答案非常相似,但将父对象复制逻辑包装在构造函数中,而不是将其置于new Child()调用之外.

  • 这种方法的缺点是维护.如果在父项中添加字段,则还必须知道在子项的构造函数中插入赋值.在这种情况下,这似乎很简单.在更复杂的环境中,这可以而且将被遗忘.这就是为什么我更喜欢用反射方法. (5认同)

say*_*aee 6

我喜欢这样:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)


Law*_*Man 6

这就是我从我的解决方案中提出的。

    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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)