如何获取当前属性的PropertyDescriptor?

Yur*_*riy 11 .net c# propertydescriptor

我怎样才能获得PropertyDescriptor当前的房产?例如:

[MyAttribute("SomeText")]
public string MyProperty
{
    get{....}
    set
    {
        // here I want to get PropertyDescriptor for this property.
    }
}
Run Code Online (Sandbox Code Playgroud)

Wra*_*ath 15

你可以试试这个:


        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 ];
            }
        }
Run Code Online (Sandbox Code Playgroud)

  • ou ...很好,我可以编写System.ComponentModel.PropertyDescriptorCollection pdc = System.ComponentModel.TypeDescriptor.GetProperties(this); 在我的构造函数中只使用一次...谢谢! (2认同)

tod*_*dmo 9

这是一个可重复使用的转换函数,适用于那些寻找一般函数的帖子:

public static PropertyDescriptor GetPropertyDescriptor(PropertyInfo PropertyInfo)
{
    return TypeDescriptor.GetProperties(PropertyInfo.DeclaringType).Item(PropertyInfo.Name);
}
Run Code Online (Sandbox Code Playgroud)

这是一个扩展方法:

public static PropertyDescriptor PropertyDescriptor(this PropertyInfo propertyInfo)
{
  return TypeDescriptor.GetProperties(propertyInfo.DeclaringType)[propertyInfo.Name];
}
Run Code Online (Sandbox Code Playgroud)


IAb*_*act 5

我发现以下工作:

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

        //  get specific descriptor
        PropertyDescriptor property = properties.Find ( PropertyName, false );
Run Code Online (Sandbox Code Playgroud)

where PropertyName是传递给方法的值.