[英]asp.net C# : Get the name of property in delegate
I want to increase the maintainability by passing a delegate rather than a const string. 我想通过传递委托而不是const字符串来提高可维护性。 What I've done is like this; 我所做的就是这样;
var propertyName = SprintMetrics.GetNameOf(metric => metric.Productivity); //Should be : "Productivity"
and: 和:
public static string GetNameOf(Func<SprintMetrics, double> valueFunc)
{
return valueFunc.GetMethodInfo().Name; //Result is : <Excute>b_40....
}
During the debug, I walked throw "valueFunc", and there was no "Productivity" anywhere. 在调试过程中,我走路抛出“ valueFunc”,而在任何地方都没有“生产力”。
Is there any way to get the property's name "Productivity"? 有什么办法可以获取酒店的名称“生产力”? Thanks. 谢谢。
According to Access Denied's answer below, it can be done by both of the following: 根据下面的“拒绝访问”的答案,可以通过以下两种方法来完成:
var p = nameof(SprintMetrics.Productivity); //"Productivity"
var metrics = new SprintMetrics();
p = nameof(metrics.Productivity); //"Productivity"
I walked throw "valueFunc", and there was no "Productivity" anywhere. 我走路扔了“ valueFunc”,却没有“生产力”。
That's because valueFunc
is simply an anonymous function that returns the value of the Productivity
property since that's how you defined the delegate. 这是因为valueFunc
只是一个匿名函数,它返回Productivity
属性的值,因为这是您定义委托的方式。
If instead you want to inspect the delegate then use Expression
instead: 相反,如果要检查委托,则使用Expression
:
public static string GetNameOf<T>(Expression<Func<SprintMetrics, T>> valueFunc)
{
var expression = (MemberExpression)valueFunc.Body;
return expression.Member.Name;
}
Of course, you'll want to add error handling (what if action.Body
is not a MemberExpression
? What if it refers to a field and not a property?). 当然,你需要添加错误处理(如果有什么action.Body
不是MemberExpression
?如果什么它指的是一个字段,而不是财产?)。 You can see a more complete example in this answer 您可以在此答案中看到更完整的示例
You can use C# keyword nameof which was designed for this task: 您可以使用为此任务设计的C#关键字nameof:
var propertyName = nameof(metric.Productivity)
For more info take a look at the following article . 有关更多信息,请参见以下文章 。
As for your code in order to extract property name from lambda expressions you can use the following method (And there is no need to have input Func parameter in that case): 对于从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;
}
And you can call it this way: GetPropertyName(() => metric.Productivity)
您可以这样称呼: GetPropertyName(() => metric.Productivity)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.