次のクラス 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のようなメンバー関数を起動する必要があります。)
すべてのアイデアをありがとう!