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 ではなく) ターゲットを指定する必要があります。実行時にこのクラス インスタンスの特定のプロパティを取得するにはどうすればよいですか?

4

3 に答える 3

1

すでに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 });
于 2012-09-04T14:11:42.767 に答える
0

PropertyInfoを使用して、必要なプロパティの値を取得します。

于 2012-09-04T14:06:44.477 に答える
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(...);
               }
         }
  }
于 2012-09-04T14:16:47.227 に答える