我有一个包含一些属性的类。一些特定的属性用属性修饰。例如:
public class CoreAddress
{
private ContactStringProperty _LastName;
[ChangeRequestField]
public ContactStringProperty LastName
{
//ContactStringProperty has a method SameValueAs(ContactStringProperty other)
get { return this._LastName; }
}
.....
}
我想在我的类中有一个方法,它遍历该类的所有属性,过滤具有此自定义属性的属性并调用找到的属性的成员。这是我目前所拥有的:
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 });
}
}
如果此方法是属性的实例方法,我必须提供一个目标(而不是代码中的 null)。如何在运行时获取此类实例的特定属性?
最佳答案
因为您已经有了 PropertyInfo,您可以调用 GetValue method
.所以……
MethodInfo method = p.PropertyType.GetMethod("SameValueAs");
//problem solved
var propValue = p.GetValue(this);
var res = method.Invoke(propValue, new object[] { other.LastName });
关于c# - 通过特定属性过滤类实例的属性并调用属性的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12265147/