簡體   English   中英

asp.net C#:獲取委托中的屬性名稱

[英]asp.net C# : Get the name of property in delegate

我想通過傳遞委托而不是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"

我走路扔了“ 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 ?如果什么它指的是一個字段,而不是財產?)。 您可以在此答案中看到更完整的示例

您可以使用為此任務設計的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM