如何评估lambda表达式来确定对象类型 [英] How to evaluate a lambda expression to determine object type

查看:176
本文介绍了如何评估lambda表达式来确定对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Tomato
{}
public class Potato
{}
public class UIPotatoBinding(Expression< Func< object>>表达式)
{
//这里要放置什么来确保lambda结果在土豆
}
public class UITomatoBinding(Expression< Func< object>> expression)
{
//我需要在这里确定哪些代码来确定在
//中传递的lambda表达式是否导致Tomato,List< Tomato>,IEnumerable< Tomato>,ObservableCollection&番茄>
// TomatoCollection,或其他一些番茄相关的Linq构造。
}

这个lambda的东西对我来说还是陌生的。如果我问了一些已经在别的地方回答过的问题,我很抱歉。

解决方案

将在linqpad中运行,如果你有它。

  void Main()
{
表达式&对象>> f =()=>新马铃薯();
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(未知);
}
}


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.
}

This lambda stuff is still foreign to me. I apologize if I am asking something obvious that has been answered elsewhere already.

解决方案

Here is an example to do what you want. Will run in linqpad if you have it.

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");
    }
}

这篇关于如何评估lambda表达式来确定对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆