3

我有一堂课

public class News : Record
{
    public News()
    {
    }

    public LocaleValues Name { get; set; }
    public LocaleValues Body;
}

在我的LocaleValues课堂上,我有:

public class LocaleValues : List<LocalizedText>
{
    public string Method
    {
        get
        {
            var res = System.Reflection.MethodBase.GetCurrentMethod().Name;
            return res;
        }
    }
}

当我进行这样的调用时,我需要该Method属性返回属性名称的字符串表示形式:Name

var propName = new News().Name.Method;

我怎样才能做到这一点?感谢您的时间!

4

1 回答 1

10

如果您真的指的是当前属性(问题标题):

public static string GetCallerName([CallerMemberName] string name = null) {
    return name;
}
...

public string Foo {
    get {
        ...
        var myName = GetCallerName(); // "Foo"
        ...
    }
    set { ... }
}

这会将工作推送到编译器而不是运行时,并且无论内联、混淆等如何都可以工作。请注意,这需要C# 5 和 .NET 4.5 或类似的using指令。using System.Runtime.CompilerServices;

如果你的意思是这个例子:

var propName = new News().Name.Method;

那么直接从该语法中是不可能的;.Name.Method()会在.Name- 的结果上调用某些东西(可能是扩展方法),但这只是另一个对象,对它的来源一无所知(例如Name属性)。理想情况下Name,表达式树是最简单的方法。

Expression<Func<object>> expr = () => new News().Bar;

var name = ((MemberExpression)expr.Body).Member.Name; // "Bar"

可以封装为:

public static string GetMemberName(LambdaExpression lambda)
{
    var member = lambda.Body as MemberExpression;
    if (member == null) throw new NotSupportedException(
          "The final part of the lambda is not a member-expression");
    return member.Member.Name;
}

IE

Expression<Func<object>> expr = () => new News().Bar;
var name = GetMemberName(expr); // "Bar"
于 2013-03-11T07:32:53.993 回答