如何通过向继承的类添加属性来初始化对象

本文关键字:属性 初始化 对象 添加 何通过 继承 | 更新日期: 2023-09-27 18:17:16

是否有一种方法可以通过在c#中使用Linq的声明中使用继承对象来轻松地声明一个对象是另一个对象的扩展?下面的例子是我想要发生的事情。我试图避免重写超类的所有属性。

的例子:

public class Thing {
    public int Property {get; set;}
}
public class AnotherThing : Thing {
    public string AnotherProperty {get;set;}
}
public class Main {
    public List<AnotherThing> GetAnotherThings() =>
        GetListOfThings().Select(t => new AnotherThing(t) 
            { AnotherProperty = "Hello" }
        ).ToList();
    public List<Thing> GetListOfThings() {...}
}

如何通过向继承的类添加属性来初始化对象

你应该在代码的某个地方设置这些属性;在linq查询或构造函数中。
作为一个选项,AnotherThing可以这样设置:

public class AnotherThing : Thing 
{
    AnotherThing (Thing value)
    {
        this.Property = value.Property;
    }
    public string AnotherProperty {get;set;}
}

您需要在AnotherThing上编写一个构造函数,该构造函数接受Thing,并基于。恐怕没有捷径可走了。

public AnotherThing (Thing thing)
{
    this.Property = value.Property;
    // i would be careful to either make this a deep copy,
       //or have a DeepClone() method on Thing
}

如果有私有字段不能从构造函数中挖掘出来,那么在Thing上创建一个返回Memento对象的方法可能是一个好主意。我建议不要在Thing中使用返回AnotherThing的方法。

编辑:

您是否试图创建Thing以创建AnotherThing,从AnotherThing调用Thing构造函数是否更适合您的需求?: public AnotherThing (int foo) : base(foo){}