下面小编就为大家分享一篇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# 表达式目录树的应用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程学习网。
沃梦达教程
本文标题为:C# 表达式目录树的应用详解
猜你喜欢
- c# 模拟线性回归的示例 2023-03-14
- 在C# 8中如何使用默认接口方法详解 2023-03-29
- C# 使用Aspose.Cells 导出Excel的步骤及问题记录 2023-05-16
- Unity Shader实现模糊效果 2023-04-27
- .NET CORE DI 依赖注入 2023-09-27
- Oracle中for循环的使用方法 2023-07-04
- 如何使用C# 捕获进程输出 2023-03-10
- user32.dll 函数说明小结 2022-12-26
- WPF使用DrawingContext实现绘制刻度条 2023-07-04
- Unity3D实现渐变颜色效果 2023-01-16