I have a class with some properties in it. Some specific properties are decorated with an attribute. For example:
public class CoreAddress
{
private ContactStringProperty _LastName;
[ChangeRequestField]
public ContactStringProperty LastName
{
//ContactStringProperty has a method SameValueAs(ContactStringProperty other)
get { return this._LastName; }
}
.....
}
I want to have a method in my class which walks through all my properties of this class, filters the one with this custom attribute and invokes a member of the found properties. This is what I have so far:
foreach (var p in this.GetType().GetProperties())
{
//checking if it's a change request field
if (p.GetCustomAttributes(typeof(ChangeRequestFieldAttribute), false).Count() > 0)
{
MethodInfo method = p.PropertyType.GetMethod("SameValueAs");
//problem here
var res = method.Invoke(null, new object[] { other.LastName });
}
}
If this method is an instance method of the property I have to provide a target (instead of null as in the code). How do I get the specific property of this class instance at runtime?
Since you already have the PropertyInfo, you can call the
GetValue method. So…