如何使用C#传递类的多属性作为方法的参数

时间:2015-01-07 05:33:41

标签: c#

我有一个类将继承在另一个类中。课程内容:

public T First(Expression<Func<T, string>> OrderBy = null)
{
   string orderby=string.Empty;
   if (OrderBy != null)
   {
      System.Reflection.PropertyInfo orderbyinfo= (System.Reflection.PropertyInfo)  ((MemberExpression)OrderBy.Body).Member;
            orderby = orderbyinfo.Name;
   }
   ...

}

但错误“无法将lambda表达式转换为委托类型...”,方法为:

public T First(Expression<Func<T, string>> OrderBy = null,Expression<Func<T, string>> GroupBy = null)
{
   string orderby=string.Empty;
   string groupby=string.empty
   if (OrderBy != null)
   {
      System.Reflection.PropertyInfo orderbyinfo= (System.Reflection.PropertyInfo)   ((MemberExpression)OrderBy.Body).Member;
            orderby = orderbyinfo.Name;
   }

   if (GroupBy != null)
   {
      System.Reflection.PropertyInfo groupbyinfo= (System.Reflection.PropertyInfo)  ((MemberExpression)GroupBy.Body).Member;
            groupby = groupbyinfo.Name;
   }
   ...

}

方法为:

Article article = new Article();
article.Title="test";
article=article.First(x=>x.Title,y=>y.Status);

请帮帮我!感谢!!!

1 个答案:

答案 0 :(得分:1)

您收到此错误是因为Status可能不是string而您的Func只能返回string

public T First(
    Expression<Func<T, string>> orderBy = null,
    Expression<Func<T, string>> groupBy = null)

如果你把它们变成通用的,你就可以返回任何东西。由于这两个属性可能属于不同类型,因此您需要两种泛型类型(TProperty1 TProperty2),每种类型对应一种:

public T First<TProperty1, TProperty2>(
    Expression<Func<T, TProperty1>> orderBy = null, 
    Expression<Func<T, TProperty2>> groupBy = null)

示例:

class C<T>
{        

    public T First<TProperty1, TProperty2>(
        Expression<Func<T, TProperty1>> orderBy = null, 
        Expression<Func<T, TProperty2>> groupBy = null)
    {
        string orderByName = string.Empty;
        string groupByName = string.Empty;
        if (orderBy != null)
        {
            System.Reflection.PropertyInfo orderByInfo = (System.Reflection.PropertyInfo)((MemberExpression)orderBy.Body).Member;
            orderByName = orderByInfo.Name;
        }

        if (groupBy != null)
        {
            System.Reflection.PropertyInfo groupByInfo = (System.Reflection.PropertyInfo)((MemberExpression)groupBy.Body).Member;
            groupByName = groupByInfo.Name;
        }
        ....
    }
}

用法:这两个属性都是int s

new C<string>().First(x => x.Length, x => x.Length);

但是如果它们必须是string s,那么您需要将值转换/转换为string s:

article = article.First(x=>x.Title, y=>y.Status.ToString());

您是否已阅读所有错误消息并在此处发布所有错误消息,您会注意到有一行告诉您转换错误:

  

错误1无法将lambda表达式转换为委托类型'System.Func',因为块中的某些返回类型不能隐式转换为委托返回类型

     

错误2无法将类型'int'隐式转换为'string'