簡體   English   中英

如何獲取F的Func中使用的屬性名稱字符串

[英]How can I get property name strings used in a Func of T

我有一個場景,我必須得到一個字符串數組,代表Func參數中使用的每個屬性名稱。 這是一個示例實現:

public class CustomClass<TSource>
{
  public string[] GetPropertiesUsed
  {
    get
    {
      // do magical parsing based upon parameter passed into CustomMethod
    }
  }

  public void CustomMethod(Func<TSource, object> method)
  {
    // do stuff
  }
}

這是一個示例用法:

var customClass = new CustomClass<Person>();
customClass.CustomMethod(src => "(" + src.AreaCode + ") " + src.Phone);

...

var propertiesUsed = customClass.GetPropertiesUsed;
// propertiesUsed should contain ["AreaCode", "Phone"]

我在上面堅持的部分是“根據傳遞給CustomMethod的參數進行魔法解析”。

您應該使用Expression<Func<>>類。 表達式包含實際的樹,並且可以很容易地被編譯以獲得委托(這是一個func)。 你真正想做的是看表達的主體和理由。 Expression類為您提供所有必要的基礎結構。

您需要更改CustomMethod以獲取Expression<Func<TSource, object>> ,並且可能是ExpressionVisitor子類,覆蓋VisitMember

public void CustomMethod(Expression<Func<TSource, object>> method)
{
     PropertyFinder lister = new PropertyFinder();
     properties = lister.Parse((Expression) expr);
}

// this will be what you want to return from GetPropertiesUsed
List<string> properties;

public class PropertyFinder : ExpressionVisitor
{
    public List<string> Parse(Expression expression)
    {
        properties.Clear();
        Visit(expression);
        return properties;
    }

    List<string> properties = new List<string>();

    protected override Expression VisitMember(MemberExpression m)
    {
        // look at m to see what the property name is and add it to properties
        ... code here ...
        // then return the result of ExpressionVisitor.VisitMember
        return base.VisitMember(m);
    }
}

這應該讓你開始朝着正確的方向前進。 如果您需要幫助找出“......代碼......”部分,請告訴我。

有用的鏈接:

暫無
暫無

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

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