我有以下类 Point 和 Class2。我的目的是在 Class2 中检索所有 Points 实例以将它们存储在列表中。
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/
...
(我想这样做:最后一个类将具有取决于数据库的 Point 实例,所以我不知道我将拥有多少 Point,并且我需要启动像 Addition 这样的成员函数。)
感谢所有的想法!