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

时间:2013-08-30 15:22:12

标签: c# reflection casting

我有以下类Point和Class2。我的目的是在Class2中检索所有Points的实例以将它们存储在List中。

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实例,这取决于db,所以我不知道我将拥有多少Point,并且我需要启动一个像Addition这样的成员函数。)

感谢所有想法!

3 个答案:

答案 0 :(得分:6)

使用FieldInfo.GetValue()方法:

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

答案 1 :(得分:1)

问题出在你正在使用的GetFields电话中。默认情况下,GetFields返回所有公共实例字段,您的点被声明为私有实例字段。您需要使用other overload,这样可以对您获得的字段进行更细粒度的控制

如果我将该行更改为:

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

答案 2 :(得分:0)

不知道这是否会起作用,但不是我的头脑:

public List<Point> getAllPoint() 
        {
            return (from field in this.GetType().GetFields() where field.FieldType == typeof(Point) select (Point)field.GetValue(this)).ToList();
        }