質問

どうすれば手に入れることができますか PropertyDescriptor 現在のプロパティのために?例えば:

[MyAttribute("SomeText")]
public string MyProperty
{
    get{....}
    set
    {
        // here I want to get PropertyDescriptor for this property.
    }
}
役に立ちましたか?

解決

あなたはこれを試すことができます:


        public string Test
        {
            get
            {
                //Get properties for this
                System.ComponentModel.PropertyDescriptorCollection pdc = System.ComponentModel.TypeDescriptor.GetProperties( this );

                //Get property descriptor for current property
                System.ComponentModel.PropertyDescriptor pd = pdc[ System.Reflection.MethodBase.GetCurrentMethod().Name ];
            }
        }

他のヒント

一般的な機能を探しているこの投稿に到達した人のための再利用可能な変換機能は次のとおりです。

public static PropertyDescriptor GetPropertyDescriptor(PropertyInfo PropertyInfo)
{
    return TypeDescriptor.GetProperties(PropertyInfo.DeclaringType).Item(PropertyInfo.Name);
}

拡張方法は次のとおりです。

public static PropertyDescriptor PropertyDescriptor(this PropertyInfo propertyInfo)
{
  return TypeDescriptor.GetProperties(propertyInfo.DeclaringType)[propertyInfo.Name];
}

私は次のことが機能することがわかりました:

        //  get property descriptions
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties ( this );

        //  get specific descriptor
        PropertyDescriptor property = properties.Find ( PropertyName, false );

どこ PropertyName 値はメソッドに渡されます。

これはどう?

this.GetType().GetProperty("MyProperty")

文字列なしでこれを行うことができるかどうかを尋ねていると思います。つまり、「このプロパティ」を表す他のトークンです。私はそれが存在するとは思わない。しかし、とにかくこのコードを書いているので(?)、コードにプロパティの名前を入れるだけで難しいことは何ですか?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top