使用ExpandoObject创建动态类

 

Dictionary<string, object> propertyDic = new Dictionary<string, object>() {

{ "p1",1},
{ "p2",1.34D},
{ "p3","你好呀"},
{ "p4",new{ Id = 1, Name = "zhangsan"} },
{ "TestAction1",()=>{Console.WriteLine("我执行了委托TestAction1"); } },
{ "TestAction2",(string arg)=>{Console.WriteLine($"我执行了委托TestAction2 {arg}"); } },
{ "TestFunc1",()=>{Console.WriteLine("我执行了委托TestFunc1");return "我是委托TestFunc1返回值"; } },
{ "TestFunc2",(string arg)=>{Console.WriteLine($"我执行了委托TestFunc1 {arg}"); return "我是委托TestFunc2返回值";} },
};
dynamic dynamicObject = new System.Dynamic.ExpandoObject();
var dic = (IDictionary<string, object>)dynamicObject;
foreach (var item in propertyDic)
{
dic[item.Key] = item.Value;
}

Console.WriteLine(dynamicObject.p1);
Console.WriteLine(dynamicObject.p2);
Console.WriteLine(dynamicObject.p3);
Console.WriteLine(dynamicObject.p4);
dynamicObject.TestAction1.Invoke();
dynamicObject.TestAction2.Invoke("我是传进去的参数");
Console.WriteLine(dynamicObject.TestFunc1.Invoke());
Console.WriteLine(dynamicObject.TestFunc2.Invoke("我是传进去的参数"));

 

复制运行一下吧,突然发现好神奇,可以实现动态生成,属性字段由你决定,委托也可以。

 

posted @ 2022-07-16 10:56  晨晞gg  阅读(72)  评论(0编辑  收藏  举报