简体   繁体   English

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

[英]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.

相关问题 如何在 api model 验证过程 asp.net Z240AA2CEC4B29DCC56F3BEE520E 中获取父属性名称? - How to get parent property name in api model validation process asp.net c#? 在ASP.NET C#中获取域名和/或子站点名称 - Get domain and/ or subsite name in asp.net c# 在ASP.NET C#中仅从ldap获取名称 - Get just the name from ldap in asp.net c# 如何在 ASP.NET / C# 中获取客户端计算机名称? - How to get Client Machine Name in ASP.NET / C#? C#中的ASP.NET:QueueUserWorkItem中的自定义委托函数未更新 - ASP.NET in C#: custom delegate function in QueueUserWorkItem not updating 错误:在所选数据源(asp.net c#,sql)上找不到名称为“ ProductID”的字段或属性 - Error: A field or property with the name 'ProductID' was not found on the selected data source (asp.net c#, sql) 使用列表时打印属性名称 <List<> &gt;使用C#在ASP.NET中作为中继器数据源进行收集 - Print property name when using a List<List<>> Collection as a Repeater Datasource in ASP.NET with C# 在C#中访问控件属性的属性 - access property of property of control in asp.net C# 在C#中获取ASP.NET中的路径 - Get Path in asp.net for c# 如何从asp:FileUpload获取文件名并使用ASP.NET和C#显示在标签中 - How to get file name from asp:FileUpload and display in a Label using ASP.NET and C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM