【问题标题】:passing a property to get it's value (as an expression?)传递一个属性来获取它的值(作为一个表达式?)
【发布时间】:2011-02-25 19:23:04
【问题描述】:

我想我应该能够使用某种表达式作为下面最终方法的参数,但我无法解决它。

我该怎么做?

干杯,
浆果

class Detail{
    string DisplayName{get;set;}
    string SpanishName{get;set;}
    string FrenchName{get;set;}
}

class Master{
    IEnumerable<Detail> AllDetail{get;set;}
    bool DoSpanish(get;set;)
    bool DoFrench(get;set;)

    _flipDisplayName(){
        DoSpanish 
            ? _flipDisplayName(x=>x.SpanishName) 
            : _flipDisplayName(x=>x.FrenchName);
    }

    // *****************************************************
    _flipDisplayName(????){ <==== Expression??
            foreach(Detail detail in AllDetail) detail.DisplayName = ???;
    }

}

【问题讨论】:

    标签: c# linq expression


    【解决方案1】:

    试试类似的东西

    _flipDisplayName(Func<Detail, string> name){ 
         foreach(Detail detail in AllDetail)
             detail.DisplayName = name(detail); 
    }
    

    由于不需要分析传入的表达式,Func&lt;,&gt; 就足够了。

    您也可以使用Expression&lt;Func&lt;,&gt;&gt;,这将允许您解析提供的表达式以确定它是指英语还是西班牙语属性,但在这种情况下这不是必需的。

    【讨论】:

      【解决方案2】:

      如果我正确理解你的目标,你可以这样做:

      private void _flipDisplayName(Func<Detail, string> displayFunc)
      {
              foreach(Detail detail in AllDetail) 
                  detail.displayFunc(detail);
      }
      

      另一个重载可能是:

      private void _flipDisplayName()
      {
          this.DoSpanish ? _flipDisplayName(x => x.SpanishName) 
                         : _flipDisplayName(x => x.FrenchName);
      }
      

      【讨论】:

        【解决方案3】:

        查看Get value from ASP.NET MVC Lambda Expression。那是在 MVC 的上下文中,但答案适用于任何地方。

        【讨论】:

        • Marcind 是对的 - 我已经回答了你实际提出的问题,但他正在回答你真正需要的问题 :)
        猜你喜欢
        • 2011-05-09
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多