根据特定属性过滤类实例的属性并调用属性方法

4

我有一个类,其中包含一些属性。其中某些特定属性被装饰了一个属性。例如:

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)。我在运行时如何获取该类实例的特定属性?


如果你已经完全了解这个类,为什么还要使用反射呢?或者你想处理一些子类的属性? - Pavel Voronin
它实际上用于避免大量容易出错的手动属性检查,而且当开发人员添加具有此属性的属性时,它会自动包含在上述方法中。 - hoetz
3个回答

1

既然您已经拥有 PropertyInfo,您可以调用 GetValue 方法。所以...

MethodInfo method = p.PropertyType.GetMethod("SameValueAs");
//problem solved
var propValue = p.GetValue(this);

var res = method.Invoke(propValue, new object[] { other.LastName });

0
使用 PropertyInfo 来获取您需要的任何属性的值。

0

只需从属性中获取值,然后像平常一样使用它即可。

foreach (var p in type.GetProperties())
{
         if (p.GetCustomAttributes(typeof(ChangeRequestFieldAttribute), false).Count() > 0)
         {

               //just get the value of the property & cast it.
               var propertyValue = p.GetValue(<the instance>, null);
               if (propertyValue !=null && propertyValue is ContactStringProperty)
               {
                   var contactString = (ContactStringProperty)property;
                   contactString.SameValueAs(...);
               }
         }
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接