c# 是否可以更改 parent 的 class 的字段类型?
c# is it possible to change the field type of parent's class?
如果我有 2 个 classes
一个用于数据,例如:
public class Cords
{
public double x;
public double y;
}
还有一个,使用此数据:
public class Geometry
{
public Cords()
{
points = new List<Cords>();
}
public void SomeMathWithPoints()
{
MagicWithPoints(points);
}
protected List<Cords> points;
}
我想用一些特定的功能扩展这个 class,使用继承,但是这次我需要一些 Cords class 的附加数据。
所以我正在尝试这样做:
public class ExtendedCords: Cords
{
public double x;
public double y;
public string name;
}
public class ExtendedGeometry : Geometry
{
protected SomeNewMagicWithPoints(){...}
protected List<ExtendedCords> points;
}
但我注意到,如果我愿意的话:
ExtendedGeometry myObject = new ExtendedGeometry();
myObject.SomeMathWithPoints();
此函数将使用旧(父母)字段 points
。那么我怎样才能让它使用类型为 ExtendedCords
的新对象呢?我的意思是,我希望能够在新领域同时使用 child 和 parrent 的功能。
为 Geometry
基础 class 和虚拟方法使用通用类型:
public class Geometry<TCord> where TCord : Cords
{
public void InitCords(){
points = new List<TCord>();
}
public virtual void SomeMathWithPoints(){
MagicWithPoints(points);
};
protected List<TCord> points;
}
然后在您的分机中,
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>
}
如果我有 2 个 classes 一个用于数据,例如:
public class Cords
{
public double x;
public double y;
}
还有一个,使用此数据:
public class Geometry
{
public Cords()
{
points = new List<Cords>();
}
public void SomeMathWithPoints()
{
MagicWithPoints(points);
}
protected List<Cords> points;
}
我想用一些特定的功能扩展这个 class,使用继承,但是这次我需要一些 Cords class 的附加数据。 所以我正在尝试这样做:
public class ExtendedCords: Cords
{
public double x;
public double y;
public string name;
}
public class ExtendedGeometry : Geometry
{
protected SomeNewMagicWithPoints(){...}
protected List<ExtendedCords> points;
}
但我注意到,如果我愿意的话:
ExtendedGeometry myObject = new ExtendedGeometry();
myObject.SomeMathWithPoints();
此函数将使用旧(父母)字段 points
。那么我怎样才能让它使用类型为 ExtendedCords
的新对象呢?我的意思是,我希望能够在新领域同时使用 child 和 parrent 的功能。
为 Geometry
基础 class 和虚拟方法使用通用类型:
public class Geometry<TCord> where TCord : Cords
{
public void InitCords(){
points = new List<TCord>();
}
public virtual void SomeMathWithPoints(){
MagicWithPoints(points);
};
protected List<TCord> points;
}
然后在您的分机中,
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>
}