In your example you have a field rather than a property. The below shows an example of how to iterate through all the members of a type. You can filter down using FindMembers instead of GetMemebrs
public class Reflector
{
public void ShowMembers(object o)
{
Type type = o.GetType();
foreach (MemberInfo member in type.GetMembers())
{
Console.WriteLine("{0} is a {1}", member.Name, member.MemberType);
}
}
}
Running the above code against a button and you get something like:
...skip...
ManipulationDelta is a Event
ManipulationInertiaStarting is a Event
ManipulationBoundaryFeedback is a Event
ManipulationCompleted is a Event
IsDefaultProperty is a Field
IsCancelProperty is a Field
IsDefaultedProperty is a Field
...
So just to be clear:
Public string a;
is a Field, while
public string a { get; set; }
would be a property.
I didn't actually answer the question. That's clever of me.
public class Reflector
{
public void ShowMembers(object o)
{
Type type = o.GetType();
foreach (MemberInfo member in type.GetMembers())
{
Console.WriteLine("{0} is a {1}", member.Name, member.MemberType);
}
}
public void Set(object o, string fieldName, int val)
{
MemberInfo[] info = o.GetType().GetMember(fieldName);
FieldInfo field = info[0] as FieldInfo;
field.SetValue(o, val);
}
public int x;
}
If I call reflector.Set(reflector, "x", 10); so I'm calling Set on itself, the above method will set the value to 10. If you want to read the value it is GetValue.