代码之家  ›  专栏  ›  技术社区  ›  cheny

asp.netC#:获取委托中属性的名称

  •  0
  • cheny  · 技术社区  · 7 年前

    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....
    }
    

    有没有办法把这个楼盘命名为“生产力”?谢谢。


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

    var p = nameof(SprintMetrics.Productivity); //"Productivity"
    
    var metrics = new SprintMetrics();
    p = nameof(metrics.Productivity); //"Productivity"
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Access Denied    7 年前

    var propertyName = nameof(metric.Productivity)
    

    有关更多信息,请参阅以下内容 article

    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(() => metric.Productivity)

        2
  •  2
  •   D Stanley    7 年前

    我边走边扔“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