我想通过传递委托而不是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”,而在任何地方都没有“生产力”。
有什么办法可以获取酒店的名称“生产力”?谢谢。
根据下面的“拒绝访问”的答案,可以通过以下两种方法来完成:
var p = nameof(SprintMetrics.Productivity); //"Productivity"
var metrics = new SprintMetrics();
p = nameof(metrics.Productivity); //"Productivity"
您可以使用为此任务设计的C#关键字nameof:
var propertyName = nameof(metric.Productivity)
有关更多信息,请参见以下文章。
为了从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(() => metric.Productivity)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句