说我有几个课程;
public class A {
public int value;
public A(int value) {
this.value = value;
}
}
public class B : A {
public B(int value) : base(value) { }
}
public class Base {
public A someobject;
public Base(A someobject)
{
this.someobject = someobject;
}
}
如果我想从课程Base
派生,我可以写这个;
public class Derived : Base {
public Derived(A someobject) : base(someobject) { }
}
但是,是否可以将someobject
字段的数据类型更改为派生子类,如本示例所示?
public class Derived : Base {
public B someobject;
public Derived(B someobject) : base(someobject) { }
}
答案 0 :(得分:5)
不,这是不可能的 - 这样做会很危险。请注意:您当前正在使用字段,而不是属性,它们根本不允许您覆盖它们(尽管可以隐藏基地)。但是,即使使用属性,在覆盖时仍无法更改属性的返回类型。
请考虑以下事项:
void Main()
{
Base myThing = new Derived();
//We view it as a Base object, so we can assign any Animal to MyAnimal
myThing.MyAnimal = new Cat();
//Now let's cast it back to Derived
Derived myCastThing = (Derived)myThing;
myCastThing.MyAnimal; //We expect a Dog, but we get a Cat?
}
public class Base
{
public virtual Animal MyAnimal { get; set; }
}
public class Derived : Base
{
public override Dog MyAnimal { get; set; }
}
public class Animal { }
public class Dog : Animal { }
public class Cat : Animal { }
然而,你可以使用泛型来实现你想要的东西:
public class Base<TAnimalType> where TAnimalType : Animal
{
public virtual TAnimalType MyAnimal { get; set; }
}
public class Derived : Base<Dog>
{
public override Dog MyAnimal { get; set; }
}