【C#表达式树】 反射在表达式树中的应用 ListInitExpression

以下都是反射在表达式树中的应用

【C#表达式树】 反射在表达式树中的应用 ListInitExpression

 

 

 

 案例一、Expression.MemberInit 反射获取成员(字段 或者属性),绑定数据,然后生成 成员表达式节点

 

  class Animal
        {
            public string Species { get; set; }
            public int Age { get; set; }
        }
        public static void CreateMemberInitExpression()
        {
            NewExpression newAnimal = Expression.New(typeof(Animal));
            //利用反射获取类的成员信息,保存为反射成员信息 memberinfo
            System.Reflection.MemberInfo speciesMember = typeof(Animal).GetMember("Species")[0];
            System.Reflection.MemberInfo ageMember = typeof(Animal).GetMember("Age")[0];


            //把数据绑定到成员上,相当于赋值   MemberAssignment继承MemberBinding
            MemberBinding speciesMemberBinding = Expression.Bind(speciesMember, Expression.Constant("horse"));
           MemberAssignment ageMemberBinding = Expression.Bind(ageMember, Expression.Constant(12));

            
            // 初始化成员列表
            MemberInitExpression memberInitExpression = Expression.MemberInit(newAnimal, speciesMemberBinding, ageMemberBinding);

            Console.WriteLine(memberInitExpression.ToString());

            // This code produces the following output:
            //
            // new Animal() {Species = "horse", Age = 12}
        }

 

 案例二、Expression.ListInit

//创建一个ListInitExpression表示集合初始化器
//示例:
string proner1 = "sam";
string proner2 = "korn";

MethodInfo add = typeof ( List<string> ).GetMethod ( "Add" );
//生成表达式:Add("sam")
var elm1 = Expression.ElementInit (add ,Expression.Constant ( proner1 ));
//生成表达式:Add("korn")
var elm2 = Expression.ElementInit (add ,Expression.Constant ( proner2 ));
//生成表达式:new List<string>( )
var list = Expression.New ( typeof ( List<string> ) );
//生成表达式:new List<string> { "sam" , "korn" }
var listObject = Expression.ListInit (list , elm1 , elm2);

Console.WriteLine(listObject.ToString() );

 

上一篇:多态与多态性


下一篇:Java-面向对象的三大特征--多态