据我所知,似乎没有将类从基类转换为继承类的好方法。
按照this中的答案问题,我已经继续并创建了一个构造函数,该构造函数将基类的实例作为参数。
构造函数如下所示:
public DerivedClass(BaseClass base) {
this.Id = base.Id;
this.Foo = base.Foo;
// ..
this.NewProperty = SomeNewValue;
}
等这也意味着,如果基类获得了一个新属性,派生类中的构造函数也需要修改才能复制该属性。
有没有办法利用派生类继承自基类这一事实来降低此构造函数的脆弱性?
请您参考如下方法:
看来你还没有完全掌握继承,你想多了你需要做什么。
I've gone ahead and just created a constructor that takes an instance of the base class as a parameter.
在扩展(继承)基类时不需要这样做,只有在包装类时才需要这样做。
Is there a way to leverage the fact that the derived class inherits from the base class to make this constructor less fragile?
是的:使用构造函数重载。给定这个基类:
public class MyBase
{
public virtual string Name { get; set;}
}
你可以这样做:
public class MyExtendedClass : MyBase
{
public MyExtendedClass(string name)
{
Name = name;
}
}
但更好的是像这样利用构造函数重载,其中构造函数参数传递给基类构造函数:
public class MyBase
{
public MyBase(string name)
{
Name = name;
}
public virtual string Name { get; set;}
}
public class MyExtendedClass : MyBase
{
public MyExtendedClass(string name) : base (name) { }
}
您倾向于在构造函数中为您希望不可变的属性传递值。对于其他人,您可以利用内联初始化:
var myNewClass = new MyExtendedClass() { Name = "blah" };
