[英]How to get PropertyDescriptor for current property?
如何獲取當前屬性的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")
我想你問你是否可以在沒有字符串的情況下做到這一點 - 即代表'this property'的其他一些標記。 我認為不存在。 但是既然你正在編寫這段代碼(?)在代碼中放置屬性的名稱有什么困難?
為了將來參考,您現在可以這樣做:
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.