C# 表达式目录树的应用详解
程序员文章站
2023-12-19 21:12:22
使用表达式目录树实现两个不同类型的属性赋值:
public class people
{
public int age { get; set; }
publ...
使用表达式目录树实现两个不同类型的属性赋值:
public class people { public int age { get; set; } public string name { get; set; } public int id; } public class peoplecopy { public int age { get; set; } public string name { get; set; } public int id; } public class class1 { private static dictionary<string, object> _dic = new dictionary<string, object>(); private static tout transexp<tin, tout>(tin tin) { string key = $"funckey_{typeof(tin).fullname}_{typeof(tout).fullname}"; if (!_dic.keys.contains(key)) { parameterexpression parameterexpression = expression.parameter(typeof(tin), "p"); list<memberbinding> memberbindinglist = new list<memberbinding>(); foreach (var item in typeof(tout).getproperties()) { propertyinfo propertyinfo = typeof(tin).getproperty(item.name); if (propertyinfo == null) { continue; } memberexpression property = expression.property(parameterexpression, propertyinfo); memberbindinglist.add(expression.bind(item, property)); } foreach (var item in typeof(tout).getfields()) { fieldinfo fieldinfo = typeof(tin).getfield(item.name); if (fieldinfo == null) { continue; } memberexpression property = expression.field(parameterexpression, fieldinfo); memberbindinglist.add(expression.bind(item, property)); } expression<func<tin, tout>> expression = expression.lambda<func<tin, tout>>(expression.memberinit(expression.new(typeof(tout)), memberbindinglist), new parameterexpression[] { parameterexpression }); func<tin, tout> func = expression.compile(); _dic.add(key,func); } return ((func < tin, tout > )_dic[key])(tin); } } static void main(string[] args) { list<classlibrary1.peoplecopy> peolecopylist = new list<classlibrary1.peoplecopy>(); for (int i = 0; i < 5; i++) { classlibrary1.people people = new classlibrary1.people() { id = 5+1, age = 25, name = "aaa"+i }; peolecopylist.add(class1.toutget<classlibrary1.people, classlibrary1.peoplecopy>(people)); } }
以上这篇c# 表达式目录树的应用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。