[英]How to evaluate a lambda expression to determine object type
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的東西對我來說還是陌生的。 如果我要問明顯的問題,已經在其他地方回答了,我深表歉意。
回應您的評論
I need to be able to handle List<Tomato>, IEnumerable<Tomato>, ObservableCollection<Tomato>, Tomato, TomatoCollection
可以在IEnumerable<Tomato>
恢復它們的前三個(可能還有最后一個)。
我看不出有什么意義,如果混合返回拉姆達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編寫,這是值得的)。
這是做您想做的例子。 如果有的話,將在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");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.