2012-02-20 82 views
2

我有这样的方法:如何传递System.Linq.LambdaExpression?

public List<MyObjects> All<TEntity>(params LambdaExpression[] exprs) 

与我可以调用它像这样的意图:

All<SomeObject>(a => a.Collection1, a=> a.Collection2, a=>a.Collection3); 

然而,我的方法的签名似乎不采取正确的表达。我究竟做错了什么?我如何编写方法签名以获得期望的效果?

编辑:我意识到,我的例子方法调用并没有准确地反映我试图在现实生活中:)

感谢做!

+0

什么是All()方法应该做的?是否假设检查集合中的项目是否满足一组谓词(类似于LINQ ['All()'](http://msdn.microsoft.com/en-us/library/bb548541.aspx)方法) ?或者它将一组集合展平成一个集合(类似于LINQ ['SelectMany()'](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx)方法)?这听起来像你应该在这里使用'SelectMany()',如果我没有弄错的话。 – 2012-02-21 20:43:01

回答

1

也许最彻底的方法在这种情况下是写一个扩展方法。

public static class MyExtensions 
{ 
    public static List<TEntity> All<TEntity, TResult>(
     this TEntity entity, 
     params Func<TEntity, TResult>[] exprs) 
    { 
     if (entity == null) 
     { 
      throw new ArgumentNullException("entity"); 
     } 
     if (exprs == null) 
     { 
      throw new ArgumentNullException("exprs"); 
     } 

     // TODO: Implementation required 
     throw new NotImplementedException(); 
    } 
} 

请注意,由于类型推断,您在调用方法时不必指定类型参数。

class C 
{ 
    public List<string> Collection1 {get; set;} 
    public List<string> Collection2 {get; set;} 
    public List<string> Collection3 {get; set;} 
    // ... 
} 
// ... 
var c = new C();    
c.All(x => x.Collection1, x => x.Collection2, x => x.Collection3); 
1

难道你的意思是像

public List<MyObjects> All(params Action<ICollection>[] exprs) 

All(a => new List<int>(), b => new List<string>(), c => new List<bool>()); 
+0

这并不完全 - 因为我需要访问传入表达式的“a”对象的属性。 Action类不是MVC框架的一部分吗?这没有连接到MVC。 – TheNerd 2012-02-20 23:07:20