C# 表達(dá)式目錄樹(shù)的應(yīng)用詳解
更新時(shí)間:2017年12月18日 10:13:23 作者:Torey_li
下面小編就為大家分享一篇C# 表達(dá)式目錄樹(shù)的應(yīng)用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
使用表達(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));
}
}
以上這篇C# 表達(dá)式目錄樹(shù)的應(yīng)用詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#驗(yàn)證用戶輸入信息是否包含危險(xiǎn)字符串的方法
這篇文章主要介紹了C#驗(yàn)證用戶輸入信息是否包含危險(xiǎn)字符串的方法,可針對(duì)and、or、exec、insert、select等SQL操作技巧進(jìn)行過(guò)濾操作,非常具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03
c# 判斷是否為空然后賦值的4種實(shí)現(xiàn)方法
下面小編就為大家分享一篇c# 判斷是否為空然后賦值的4種實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2017-12-12

