5

次のクラス Point と Class2 があります。私の目的は、Class2 ですべてのポイントのインスタンスを取得して、それらをリストに格納することです。

public class Point
    {
        int x;
        int y;
        string col;

        public Point(int abs, int ord, string clr)
        {
            this.x = abs;
            this.y = ord;
            this.col = clr;
        }

        public string toColor()
        {
            return this.col;
        }

        public int Addition()
        {
            return (this.x + this.y);
        }
    }

class Class2
    {
        int test;
        Point pt1;
        Point pt2;
        Point pt3;
        List<Point> listPt = new List<Point>() { };

        public Class2()
        {
            test = 100;
            this.pt1 = new Point(2, 3, "red");
            this.pt2 = new Point(1, 30, "blue");
            this.pt3 = new Point(5, 10, "black");
        }

        public List<Point> getAllPoint() 
        {
            foreach (var field in this.GetType().GetFields())
            {
                //retrieve current type of the anonimous type variable
                Type fieldType = field.FieldType;

                if (fieldType == typeof(Point))
                {
                    Console.WriteLine("POINT: {0}", field.ToString());
                    //listPt.Add(field); //error
                }
                else
                {
                    Console.WriteLine("Field {0} is not a Point", field.ToString());
                }
            }

            Console.ReadKey();
            return listPt;
        }
    }

しかし、フィールドのタイプが「System.Reflection.FieldInfo」であるため、機能しません。どうすれば機能しますか? 多くの記事を読みましたが、解決策が見つかりませんでした:

http://msdn.microsoft.com/en-us/library/ms173105.aspx

リフレクションを介してプロパティを設定するときの型変換の問題

http://technico.qnownow.com/how-to-set-property-value-using-reflection-in-c/

実行時にのみ認識される型に変数を変換しますか?

...

(私はそれをしたい:クラスは最後にdbに依存するPointインスタンスを持っているので、どれだけのPointを持つか分からず、Additionのようなメンバー関数を起動する必要があります。)

すべてのアイデアをありがとう!

4

3 に答える 3

9

使用FieldInfo.GetValue()方法:

listPt.Add((Point)field.GetValue(this));
于 2013-08-30T15:27:32.700 に答える
1

問題は、使用しているGetFields呼び出しにあります。デフォルトでは、GetFields はすべてのパブリック インスタンス フィールドを返し、ポイントはプライベートインスタンス フィールドとして宣言されます。他のオーバーロードを使用する必要があります。これにより、結果として取得するフィールドをより細かく制御できます

その行を次のように変更すると:

this.GetType().GetFields(BindingFlags.NonPublic|BindingFlags.Instance)

次の結果が得られます。

Field Int32 test is not a Point
POINT: Point pt1
POINT: Point pt2
POINT: Point pt3
Field System.Collections.Generic.List`1[UserQuery+Point] listPt is not a Point
于 2013-08-30T15:28:42.193 に答える