Recuperare in maniera automatica in nome della proprietà corrente.

Scritto da  Massimo Bonanni il lunedì 19 settembre 2011  •  Linguaggio: C#,VB   • Livello: 100


La classe proposta in questa pillola mette a disposizione un metodo che, se utilizzato all'interno del set o get di una property, restituisce il nome della property stessa.

VB.NET

Public NotInheritable Class PropertyHelper
    Private Sub New()
 
    End Sub
 
    Private Const SetPropertyPrefix = "set_"
    Private Const GetPropertyPrefix = "get_"
 
    Public Shared Function GetCurrentPropertyName() As String
        Dim retval As String = Nothing
        Dim method = (From sf In New StackTrace().GetFrames
                    Where sf.GetMethod().DeclaringType <> GetType(PropertyHelper)
                    Select sf.GetMethod()).FirstOrDefault()
        If method IsNot Nothing Then
            If method.Name.StartsWith(SetPropertyPrefix) Then
                retval = method.Name.Replace(SetPropertyPrefix, "")
            End If
            If method.Name.StartsWith(GetPropertyPrefix) Then
                retval = method.Name.Replace(GetPropertyPrefix, "")
            End If
        End If
        Return retval
    End Function
End Class

 

C#

public static class PropertyHelper
{
    private const string SetPropertyPrefix = "set_";
    private const string GetPropertyPrefix = "get_";
 
    public static string GetCurrentPropertyName()
    {
        string retval=null;
 
        var method=(from sf in new StackTrace().GetFrames()
                    where sf.GetMethod().DeclaringType != typeof(PropertyHelper)
                    select sf.GetMethod()).FirstOrDefault();
        if (method != null)
        {
            if (method.Name.StartsWith(SetPropertyPrefix))
            {
                retval=method.Name.Replace(SetPropertyPrefix,"");
            }
            if (method.Name.StartsWith(GetPropertyPrefix))
            {
                retval = method.Name.Replace(GetPropertyPrefix, "");
            }
        }
        return retval;
    }
}


La classe può essere utilizzata, ad esempio, in quelle classi in cui si implementa l'interfaccia INotifyPropertyChanged per non cablare il nome della proprietà all'interno dell'evento dell'interfaccia.


Tags: Reflection

 
x