C# 利用接口实现C语言中的多态性#

C# 利用接口实现C语言中的多态性#,c#,interface,polymorphism,stack-overflow,quadtree,C#,Interface,Polymorphism,Stack Overflow,Quadtree,通过介绍,我创建了一个基本的四叉树引擎,用于个人学习。我希望这个引擎能够处理许多不同类型的形状(目前我使用的是圆和正方形),这些形状都会在窗口中移动,并在发生碰撞时执行某种操作 在前面就泛型列表的主题提出了一个问题之后,我决定使用多态性接口。最好的界面是使用Vector2的界面,因为在我的四叉树中出现的每个对象都有一个x,y位置,Vector2很好地覆盖了这个位置。以下是我目前的代码: public interface ISpatialNode { Vector2 position {

通过介绍,我创建了一个基本的四叉树引擎,用于个人学习。我希望这个引擎能够处理许多不同类型的形状(目前我使用的是圆和正方形),这些形状都会在窗口中移动,并在发生碰撞时执行某种操作

在前面就泛型列表的主题提出了一个问题之后,我决定使用多态性接口。最好的界面是使用
Vector2
的界面,因为在我的四叉树中出现的每个对象都有一个x,y位置,
Vector2
很好地覆盖了这个位置。以下是我目前的代码:

public interface ISpatialNode {
    Vector2 position { get; set; }
}

public class QShape {
    public string colour { get; set; }
}

public class QCircle : QShape, ISpatialNode {
    public int radius;
    public Vector2 position {
        get { return position; }
        set { position = value; }
    }
    public QCircle(int theRadius, float theX, float theY, string theColour) {
        this.radius = theRadius;
        this.position = new Vector2(theX, theY);
        this.colour = theColour;
    }
}

public class QSquare : QShape, ISpatialNode {
    public int sideLength;
    public Vector2 position {
        get { return position; }
        set { position = value; }
    }
    public QSquare(int theSideLength, float theX, float theY, string theColour) {
        this.sideLength = theSideLength;
        this.position = new Vector2(theX, theY);
        this.colour = theColour;
    }
}
因此,我最终希望有一个界面,可以使用generic list
list QObjectList=new list()QObjectList.add(新的QCircle(50400300,“红色”))向它添加形状
QObjectList.Add(新的QSquare(100400300,“蓝色”)或类似的东西(请记住,稍后我会沿着这条线添加不同的形状)

问题是,当我从这里调用它时,该代码似乎不起作用(
Initialize()
是XNA方法):

所以我的问题有两部分:

1。为什么此代码在
集合中给我一个stackoverflow错误{
position=value;}
我的
QCircle
QSquare
类的一部分

2.这是否是一种高效/有效的使用接口的方法
多态性?

问题出在您的属性中,它正在循环设置自身

public Vector2 position { get ; set ; }
或者声明一个私有字段

private Vector2 _position;
public Vector2 position {
    get { return _position; }
    set { _position = value; }
}

堆栈溢出是因为:

public Vector2 position {
    get { return position; }
    set { position = value; }
}
事实上,这一套又是一样的。您可能需要:

private Vector2 _position;
public Vector2 position {
    get { return _position; }
    set { _position = value; }
}
或其简短版本:

public Vector2 position { get; set; } //BTW, the c# standard is to use upper camel case property names

关于多态性的使用,在这个场景中似乎是正确的。

选择这个答案是因为您涵盖了我的两个问题。谢谢:)我能说什么,我似乎离不开:P
public Vector2 position { get; set; } //BTW, the c# standard is to use upper camel case property names