繁体   English   中英

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

[英]How to initialize object by adding property to inherited class

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

例:

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构造函数AnotherThing更好地满足您的需求? public AnotherThing (int foo) : base(foo){}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM