2012-02-23 41 views
1

示例类:如何确定表达式成员是否属于集合类型,然后迭代该集合?

public class Procedure: SomeBaseClass 
{ 
    public Guid Id {get;set;} 
    public ICollection<Task> Tasks {get;set;} 

} 

public class Task: SomeBaseClass 
{ 
    public Guid Id {get;set;} 
    public string Name {get;set;} 
} 

方法采取在表达colelction:

public viod DoSomethingWithProperties<T>(Guid enittyId, params Expression<Func<TEntity, object>>[] propertiesToDoStuffWith) where T: SomeBaseClass 
{ 
    var item = someService<T>().FindById(entityId); 
    ....... 

    foreach(var expression in propertiesToDoStuffWith) 
    { 
    ///I need to iterate the propertiesToDetach and determine if the property is a collection so I can perform operations on each item. 
    } 

} 

我可以这样称呼它:

DoSomethingWithProperties<Procedure>(1111-1111-1111-1111-1111,p => p.tasks); 
+2

这听起来像你想使用普通的委托,而不是表达式树。 – SLaks 2012-02-23 16:37:09

+0

不应该是'foreach(var表达式在propertiesToDoStuffWith(item))'? – 2012-02-23 16:37:34

+0

@ChrisShain,我想你是对的。我唯一的问题是表达式是该类型的属性数组。我仍然想要投射表达树吗?我在想是的,但那会起作用吗? – DDiVita 2012-02-23 17:30:34

回答

1

确定type您使用编译Expressionis关键字。

foreach(var expression in propertiesToDoStuffWith) 
{ 
    var result = expression.Compile()(item); 

    if (result is ICollection){ 
      // handle collection type 
    } 
    else { 
      // some other type 
    } 
} 
+0

您需要致电代表。 – SLaks 2012-02-23 16:43:08