Come arrivare PropertyDescriptor per la proprietà attuale?
-
12-10-2019 - |
Domanda
Come posso ottenere l'PropertyDescriptor
per la proprietà attuale? Ad esempio:
[MyAttribute("SomeText")]
public string MyProperty
{
get{....}
set
{
// here I want to get PropertyDescriptor for this property.
}
}
Soluzione
Si potrebbe provare questo:
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 ];
}
}
Altri suggerimenti
Ecco una funzione di conversione riutilizzabile per coloro che ha ottenuto a questo post alla ricerca di una funzione generale:
public static PropertyDescriptor GetPropertyDescriptor(PropertyInfo PropertyInfo)
{
return TypeDescriptor.GetProperties(PropertyInfo.DeclaringType).Item(PropertyInfo.Name);
}
ed ecco un metodo di estensione:
public static PropertyDescriptor PropertyDescriptor(this PropertyInfo propertyInfo)
{
return TypeDescriptor.GetProperties(propertyInfo.DeclaringType)[propertyInfo.Name];
}
Ho trovato che il seguente ha funzionato:
// get property descriptions
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties ( this );
// get specific descriptor
PropertyDescriptor property = properties.Find ( PropertyName, false );
dove PropertyName
è un valore passato in un metodo.
Che ne dici di questo?
this.GetType().GetProperty("MyProperty")
Credo che tu stai chiedendo se si può fare questo senza la stringa - cioè qualche altro token che rappresenta 'questa proprietà'. Non credo che esista. Ma dal momento che si sta scrivendo questo codice in ogni caso (?) Che cosa è la difficoltà di mettere semplicemente il nome della proprietà nel codice?