【问题标题】:asp.net C# : Get the name of property in delegateasp.net C#:获取委托中的属性名称
【发布时间】:2018-09-07 03:41:52
【问题描述】:

我想通过传递委托而不是 const 字符串来提高可维护性。我做的是这样的;

var propertyName = SprintMetrics.GetNameOf(metric => metric.Productivity); //Should be : "Productivity"

和:

public static string GetNameOf(Func<SprintMetrics, double> valueFunc)
{
    return valueFunc.GetMethodInfo().Name; //Result is : <Excute>b_40....
}

在调试过程中,我走丢“valueFunc”,到处都没有“生产力”。

有什么方法可以获取属性的名称“Productivity”?谢谢。


根据下面拒绝访问的回答,可以通过以下两种方式完成:

var p = nameof(SprintMetrics.Productivity); //"Productivity"

var metrics = new SprintMetrics();
p = nameof(metrics.Productivity); //"Productivity"

【问题讨论】:

    标签: c# asp.net properties delegates


    【解决方案1】:

    我走了扔“valueFunc”,到处都没有“生产力”。

    这是因为 valueFunc 只是一个匿名函数,它返回 Productivity 属性的值,因为这是您定义委托的方式。

    如果您想检查委托,请改用Expression

    public static string GetNameOf<T>(Expression<Func<SprintMetrics, T>> valueFunc)
    {
        var expression = (MemberExpression)valueFunc.Body;
        return expression.Member.Name;
    }
    

    当然,您会想要添加错误处理(如果action.Body 不是MemberExpression 怎么办?如果它指的是字段而不是属性怎么办?)。你可以在this answer看到一个更完整的例子

    【讨论】:

    • 非常感谢您的提示!我会研究更多关于表达的东西:) 会有很多探索!
    【解决方案2】:

    您可以使用为此任务设计的 C# 关键字 nameof:

    var propertyName = nameof(metric.Productivity)
    

    欲了解更多信息,请查看以下article

    至于您的代码,为了从 lambda 表达式中提取属性名称,您可以使用以下方法(在这种情况下不需要输入 Func 参数):

    public static string GetPropertyName<TProperty>(Expression<Func<TProperty>> propertyLambda)
    {
        MemberExpression member = propertyLambda.Body as MemberExpression;
        if (member == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a method, not a property.",
                propertyLambda.ToString()));
    
        PropertyInfo propInfo = member.Member as PropertyInfo;
        if (propInfo == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a field, not a property.",
                propertyLambda.ToString()));
        return propInfo.Name;
    }
    

    你可以这样称呼它:GetPropertyName(() =&gt; metric.Productivity)

    【讨论】:

    • 太棒了! “nameof”可能是最简单的方法!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 2011-04-09
    • 2018-11-16
    相关资源
    最近更新 更多