使用表達(dá)式目錄樹(shù)實(shí)現(xiàn)兩個(gè)不同類型的屬性賦值:
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)); } }
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
分享文章:C#表達(dá)式目錄樹(shù)的應(yīng)用詳解-創(chuàng)新互聯(lián)
轉(zhuǎn)載來(lái)于:http://www.rwnh.cn/article42/cejehc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、自適應(yīng)網(wǎng)站、App設(shè)計(jì)、Google、用戶體驗(yàn)、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容