是否可以导出派生类的字段?

Mau*_*kye 3 c# oop inheritance field

说我有几堂课;

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

如果我想从课堂派出Base,我可以写出来;

public class Derived : Base {
    public Derived(A someobject) : base(someobject) { }
}
Run Code Online (Sandbox Code Playgroud)

但是,是否可以将someobject字段的数据类型更改为派生子类,如此示例中所示?

public class Derived : Base {
    public B someobject;

    public Derived(B someobject) : base(someobject) { }
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*Rob 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 { }
Run Code Online (Sandbox Code Playgroud)

但是,您可以使用泛型实现您想要的效果:

public class Base<TAnimalType> where TAnimalType : Animal
{
    public virtual TAnimalType MyAnimal { get; set; }
}

public class Derived : Base<Dog>
{
    public override Dog MyAnimal { get; set; }
}
Run Code Online (Sandbox Code Playgroud)