C # convert from System.Reflection.FieldInfo to custom type

I have the following Point and Class2 classes. My goal is to restore all points in Class2 instances in order to keep them in the 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; } } 

But this does not work, because the field is of type "System.Reflection.FieldInfo", how can I do this? I read a lot of articles, but I did not find a solution:

http://msdn.microsoft.com/en-us/library/ms173105.aspx

Type conversion error when setting property through reflection

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

Convert a variable to a type only known at runtime?

...

(I want to do this: at the end, the class will have Point instances depending on db, so I cannot know how many points I will have, and I will need to run a member function, for example, Addition.)

Thanks for all the ideas!

+4
source share
3 answers

Use the FieldInfo.GetValue() method:

 listPt.Add((Point)field.GetValue(this)); 
+6
source

The problem is calling GetFields that you are using. By default, GetFields returns all public instances, and your points are declared as private fields. You must use a different overload , which allows a much smaller-scale management of the fields that you get as a result

If I changed this line to:

 this.GetType().GetFields(BindingFlags.NonPublic|BindingFlags.Instance) 

I get the following result:

 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 
+1
source

I don't know if this will work, but from my head:

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

Source: https://habr.com/ru/post/1499829/


All Articles