• Dynamic Expression.Call Any


    public class Foo
        {
            public IList<string> Strings { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                //Func<Foo, bool> func =
                //    a => a.Strings.Any(b => b == "asdf");
    
                // b => b == "asdf";
                var bParameter = Expression.Parameter(typeof(string), "b");
                var asdfConstant = Expression.Constant("asdf");
                var compare = Expression.Equal(bParameter, asdfConstant);
                var compareExpression = Expression.Lambda<Func<string, bool>>(compare, bParameter);
                var ceCompareExpression = Expression.Constant(compareExpression.Compile());
    
                // a => a.Strings.Any(compareExpression)
                var parameter = Expression.Parameter(typeof(Foo), "foo");
    
                var foosProperty = Expression.Property(parameter, typeof(Foo).GetProperty("Strings"));
                MethodInfo method = typeof(Enumerable).GetMethods().Where(m => m.Name == "Any" && m.GetParameters().Length == 2).Single().MakeGenericMethod(typeof(string));
    
                var anyMethod = Expression.Call(method, foosProperty, ceCompareExpression);
    
                var lambdaExpression = Expression.Lambda<Func<Foo, bool>>(anyMethod, parameter);
    
                // Test.
                var foo = new Foo { Strings = new List<string> { "asdf", "fdsas" } };
    
                //Console.WriteLine(string.Format("original func result: {0}", func(foo)));
                Console.Write(string.Format("constructed func result: {0}", lambdaExpression.Compile()(foo)));
    
                Console.ReadKey();
            }
        }
  • 相关阅读:
    list拖动
    android sdk
    AwwwB推荐网站全盘克隆
    WPF中的容器控件——WrapPanel
    WPF中的容器控件——StackPanel
    MFC应用程序中指针的使用
    排序算法之插入排序
    转:MFC 常用语句集锦
    【转】MFC学习总结
    排序算法之冒泡排序
  • 原文地址:https://www.cnblogs.com/hyl8218/p/3208719.html
Copyright © 2020-2023  润新知