C# 表达式目录树的应用详解

使用表达式目录树实现两个不同类型的属性赋值:

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# 表达式目录树的应用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...