繁体   English   中英

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

[英]c# convert from System.Reflection.FieldInfo to user defined type

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

通过反射设置属性时键入转换问题

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

将变量转换为仅在运行时已知的类型?

...

(我想这样做:最后一个类会有Point实例,这取决于db,所以我不知道我将拥有多少Point,并且我需要启动一个像Addition这样的成员函数。)

感谢所有的想法!

使用FieldInfo.GetValue()方法:

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

问题出在您正在使用的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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM