我怎么能得到 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