栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

测试Lambda表达式相等性的最有效方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

测试Lambda表达式相等性的最有效方法

嗯…我想您必须解析树,检查每个树的节点类型和成员。我举一个例子…

using System;using System.Linq.expressions;class Test {    public string Foo { get; set; }    public string Bar { get; set; }    static void Main()    {        bool test1 = FuncTest<Test>.FuncEqual(x => x.Bar, y => y.Bar), test2 = FuncTest<Test>.FuncEqual(x => x.Foo, y => y.Bar);    }}// this only exists to make it easier to call, i.e. so that I can use FuncTest<T> with// generic-type-inference; if you use the doubly-generic method, you need to specify// both arguments, which is a pain...static class FuncTest<TSource>{    public static bool FuncEqual<TValue>(        expression<Func<TSource, TValue>> x,        expression<Func<TSource, TValue>> y)    {        return FuncTest.FuncEqual<TSource, TValue>(x, y);    }}static class FuncTest {    public static bool FuncEqual<TSource, TValue>(        expression<Func<TSource,TValue>> x,        expression<Func<TSource,TValue>> y)    {        return expressionEqual(x, y);    }    private static bool expressionEqual(expression x, expression y)    {        // deal with the simple cases first...        if (ReferenceEquals(x, y)) return true;        if (x == null || y == null) return false;        if (   x.NodeType != y.NodeType || x.Type != y.Type ) return false;        switch (x.NodeType)        { case expressionType.Lambda:     return expressionEqual(((Lambdaexpression)x).Body, ((Lambdaexpression)y).Body); case expressionType.MemberAccess:     Memberexpression mex = (Memberexpression)x, mey = (Memberexpression)y;     return mex.Member == mey.Member; // should really test down-stream expression default:     throw new NotImplementedException(x.NodeType.ToString());        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/576166.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号