0
public class Tomato
{}
public class Potato
{}
public class UIPotatoBinding(Expression<Func<object>> expression)
{
    // What to put here to make sure lambda results in Potato(s)
}     
public class UITomatoBinding(Expression<Func<object>> expression)
{
    // What code do I need to put here to determine if the lambda expression being passed in
    // results in Tomato, List<Tomato>, IEnumerable<Tomato>, ObservableCollection<Tomato>
    // TomatoCollection, or some other Tomato related Linq construct.
}

这个 lambda 东西对我来说仍然很陌生。如果我问的是已经在其他地方回答过的明显问题,我深表歉意。

4

2 回答 2

3

回应您的评论

I need to be able to handle List<Tomato>, IEnumerable<Tomato>, ObservableCollection<Tomato>, Tomato, TomatoCollection

其中前三个(可能还有最后一个)可以在IEnumerable<Tomato>.

如果混合在这些中返回的 lambda,我认为没有什么意义Tomato,可能你会更适合重载方法。

所以:

 public class MyProduce(Func<IEnumerable<Tomato>> expression)   // No need to make it an expression, so you allow for an already compiled lambda to be used.

如果你想添加Tomato

 public class MyProduce(Func<Tomato> expression) {
      Func<IEnumerable<Tomato>> expression2 = () => ( new Tomato[] { expression() });
      // Here you use expression2 as in the previous constructor.
 }

如果你想添加Potato到混合中,要么使类成为通用类,要么创建两个类共有的超类/接口。

底线是:让你的先决条件更强

如果您允许您的代码接收任何东西,您将无法对您正在处理的内容做出有效的假设,并且您的代码将最终成为很多意大利面条。允许通过object并希望您的代码处理它是禁止您使用该语言为您提供的工具(您可以用 Javascript 编写,因为它是有价值的)。

于 2013-11-15T14:49:19.253 回答
2

这是一个做你想做的事的例子。如果你有它,它将在 linqpad 中运行。

void Main()
{
    Expression<Func<object>> f = () => new Potato();
    Helper.MyProduce(f);
}


public class Tomato 
{}
public class Potato
{}

public static class Helper
{
    public static void MyProduce(Expression<Func<object>> expression)
    {
        var func = expression.Compile();
        var result = func();

        if(result is Tomato)
            Console.Write("Tomato");
        else if (result is Potato)
            Console.Write("Potato");
        else
            Console.Write("Unknown");
    }
}
于 2013-11-15T02:26:34.547 回答