从访问者内部反映属性名称?

时间:2013-11-29 13:25:53

标签: c# reflection accessor

使用反射可以从该属性的访问者中获取属性的名称吗?

任务:=

public string FindMyName
{
    get
    {
        string thisPropertyName = ??
    }
}

3 个答案:

答案 0 :(得分:4)

简单地说:不要。您可以让编译器告诉您:

public static string WhoAmI([CallerMemberName] string caller=null)
{
    return caller;
}
...
public string FindMyName
{
    get
    {
        string thisPropertyName = WhoAmI();
        //...
    }
}

这适用于OnPropertyChanged

之类的内容
protected virtual void OnPropertyChanged([CallerMemberName] string caller = null)
{
    var handler = PropertyChanged;
    if(handler != null) handler(this, new PropertyChangedEventArgs(caller));
}
...
public int Foo {
    get { return foo; }
    set { this.foo = value; OnPropertyChanged(); }
}
public string Bar {
    get { return bar; }
    set { this.bar = value; OnPropertyChanged(); }
}

答案 1 :(得分:1)

class Program
{
    static void Main()
    {
        var propertyName = Nameof<SampleClass>.Property(e => e.Name);

        MessageBox.Show(propertyName);
    }
}

public class GetPropertyNameOf<T>
{
    public static string Property<TProp>(Expression<Func<T, TProp>> exp)
    {
        var body = exp.Body as MemberExpression;
        if(body == null)
            throw new ArgumentException("'exp' should be a member expression");
        return body.Member.Name;
    }
}

答案 2 :(得分:1)

在.NET 4.5中引入CallerMemberName我相信,您可以使用此解决方法:

public static class StackHelper
{
    public static string GetCurrentPropertyName()
    {
        StackTrace st = new StackTrace();
        StackFrame sf = st.GetFrame(1);
        MethodBase currentMethodName = sf.GetMethod();
        return currentMethodName.Name.Replace("get_", "");
    }
}

用法:

public class SomeClass
{
    public string SomeProperty
    {
        get
        {
            string s = StackHelper.GetCurrentPropertyName();
            return /* ... */;
        }
    }
}