c#是否可以更改父类的字段类型?

Cra*_*yWu 1 c# oop inheritance field

如果我有2个类,一个用于数据,例如:

public class Cords
{
    public double x;
    public double y;
}
Run Code Online (Sandbox Code Playgroud)

一,使用这些数据:

public class Geometry
{
    public Cords()
    {
        points = new List<Cords>();
    }
    public void SomeMathWithPoints()
    {
         MagicWithPoints(points);
    }

    protected List<Cords> points;
}
Run Code Online (Sandbox Code Playgroud)

我想用一些特定的函数,使用继承来扩展这个类,但这次我需要一些Cords类的附加数据.所以我试着这样做:

public class ExtendedCords: Cords
{
    public double x;
    public double y;
    public string name;
}

public class ExtendedGeometry : Geometry
{
     protected SomeNewMagicWithPoints(){...}
     protected List<ExtendedCords> points;
}
Run Code Online (Sandbox Code Playgroud)

但我注意到,如果我愿意:

    ExtendedGeometry myObject = new ExtendedGeometry();
    myObject.SomeMathWithPoints();
Run Code Online (Sandbox Code Playgroud)

此函数将使用旧(parrents)字段points.那么如何让它使用一个类型的新ExtendedCords?我的意思是,我希望能够在新领域使用child和parrent的功能.

Geo*_*org 6

Geometry基类和虚方法使用泛型类型:

public class Geometry<TCord> where TCord : Cords
{
    public void InitCords(){
        points = new List<TCord>();
    }
    public virtual void SomeMathWithPoints(){
         MagicWithPoints(points);
    };

    protected List<TCord> points;
}
Run Code Online (Sandbox Code Playgroud)

然后在你的扩展中,

public class ExtendedGeometry : Geometry<ExtendedCords>
{
     public override SomeNewMagicWithPoints(){...}
     // no need for a redefinition of points since it is inherited from the base class Geometry<ExtendedCords>
}
Run Code Online (Sandbox Code Playgroud)