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));
}
}

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。

分享文章:C#表达式目录树的应用详解-创新互联
转载来于:https://www.cdcxhl.com/article42/cejehc.html

成都网站建设公司_创新互联,为您提供定制网站自适应网站App设计Google用户体验网站排名

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

手机网站建设