gpt4 book ai didi

c# 将 System.Reflection.FieldInfo 转换为用户定义的类型

转载 作者:太空狗 更新时间:2023-10-30 00:25:11 26 4
gpt4 key购买 nike

我有以下类 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

Type conversion issue when setting property through reflection

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

Convert variable to type only known at run-time?

...

(我想这样做:最后一个类将有 Point 实例,具体取决于数据库,所以我不知道我将拥有多少 Point,我将需要启动一个成员函数,如 Addition。)

感谢所有想法!

最佳答案

使用FieldInfo.GetValue()方法:

listPt.Add((Point)field.GetValue(this));

关于c# 将 System.Reflection.FieldInfo 转换为用户定义的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18536414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com