简体   繁体   English

如何获取当前属性的 PropertyDescriptor?

[英]How to get PropertyDescriptor for current property?

How can I get the PropertyDescriptor for the current property?如何获取当前属性的PropertyDescriptor For example:例如:

[MyAttribute("SomeText")]
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. 其中PropertyName是传递给方法的值。

How about this? 这个怎么样?

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

I think you're asking if you can do this without the string - ie some other token that represents 'this property'. 我想你问你是否可以在没有字符串的情况下做到这一点 - 即代表'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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM