I have the following classes Point and Class2. My purpose is to retrieve in Class2 all Points´ instances to store them in a 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 it does not work because field is of type "System.Reflection.FieldInfo", how can I do that working? I read a lot of articles but I did not find the solution:
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?
...
(I want to do that: at the end a class will have Point instances depending on a db, so I cannot know how much Point I will have, and I will need to launch a member function like Addition.)
Thank for all ideas!
Use FieldInfo.GetValue()
method:
listPt.Add((Point)field.GetValue(this));
The problem is in the GetFields call you are using. By default, GetFields returns all public instance fields, and your points are declared as private instance fields. You need to use the other overload, that allows for much more fine-grained control of the fields you are getting as a result
If I change that 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With