C# class 属性可枚举

C# class properties enumerable

我在枚举 class 时遇到问题。我在整个互联网和 Whosebug 上进行了搜索,但恐怕我对 C# 的有限经验限制了我识别确切的情况和解决方案。我的代码:

public List<annotation> annotations = new List<annotation>();

public class annotation
{
    public annotation(int pos, int x2, int y2, string artnr)
    {
        this.ArtNr = artnr;
        this.Pos = pos;
        this.X2 = x2;
        this.Y2 = y2;
    }
    public string ArtNr;
    public int Pos;
    public int X2;
    public int Y2;


}

public void add_Anno(string artnr, int x2, int y2)
{
    annotations.Add(new annotation(0,x2,y2,artnr));
}

添加服务器注释后,我想在 WPF Canvas 对象中显示它们。问题是我无法遍历列表中的所有项目。我的问题是我应该使用哪种方法进行枚举以及如何应用它?该列表包含整数和字符串。我尝试使用:

System.Collections.IEnumerator ie = annotations.GetEnumerator();
while(ie.MoveNext())
{
    annotation test = ie.GetType().GetProperties();
}

与此同时,我正在查看 "Microsoft Press Exam 7--483" 中的反射,看看这是否是一个解决方案。

谢谢。

你只需要使用foreach,它会遍历列表中的每一个元素。不需要使用反射:

foreach (var annotation in annotations)
{
    int position = annotation.Pos;
    string atrNr = annotation.ArtNr;
}

作为旁注,我建议您查看 C# Naming Conventions, and perhaps study about Properties

快速重构如下所示:

public class Annotation
{
    public Annotation(int pos, int x2, int y2, string artNr)
    {
        this.ArtNr = artNr;
        this.Pos = pos;
        this.X2 = x2;
        this.Y2 = y2;
    }

    public string ArtNr { get; private set; }
    public int Pos { get; private set; }
    public int X2 { get; private set; }
    public int Y2 { get; private set; }
}

如果您使用的是 C# 6,则可以删除 private set