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

发布时间:2020-10-13 21:40:54 作者:Torey_li
来源:脚本之家 阅读:172

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

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

推荐阅读:
  1. C#中Lambda表达式的示例分析
  2. C#中的表达式目录树

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

表达式 目录树

上一篇:pygame实现贪吃蛇游戏(上)

下一篇:Docker实现Mariadb分库分表及读写分离功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》