开发者

How to get PropertyDescriptor for current property?

How can I get the PropertyDescriptor for the current property? For example:

[MyAttribute("Some开发者_高级运维Text")]
public string MyProperty
{
    get{....}
    set
    {
        // here I want to get PropertyDescriptor for this property.
    }
}


You could try this:


        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 ];
            }
        }


Here's a re-usable conversion function for those who got to this post looking for a general function:

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

and here's an extension method:

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


I found that the following worked:

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

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

where PropertyName is a value passed into a method.


How about this?

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

I think you're asking if you can do this without the string - i.e. some other token that represents 'this property'. I don't think that exists. But since you are writing this code anyway (?) what is the difficulty in just putting the name of the property in the code?


For future reference, you can now do this:

public static PropertyDescriptor? GetPropertyDescriptor(
    this object target, 
    [CallerMemberName] string propertyName = ""
) => TypeDescriptor.GetProperties(target.GetType())
        .Find(propertyName, ignoreCase: false)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜