![](/img/trans.png)
[英]how to copy properties from one object to another with different values C#
[英]Same Variable Names - 2 Different Classes - How To Copy Values From One To Another - Reflection - C#
沒有使用AutoMapper ...(因為當他們看到依賴項時,負責這個項目的人會打磚塊)
我有一個類(A類),但有很多屬性。 我有另一個類(B類)具有相同的屬性(相同的名稱和類型)。 B類也可能有其他無關的變量。
是否有一些簡單的反射代碼可以將值從A類復制到B類?
越簡單越好。
Type typeB = b.GetType();
foreach (PropertyInfo property in a.GetType().GetProperties())
{
if (!property.CanRead || (property.GetIndexParameters().Length > 0))
continue;
PropertyInfo other = typeB.GetProperty(property.Name);
if ((other != null) && (other.CanWrite))
other.SetValue(b, property.GetValue(a, null), null);
}
這個?
static void Copy(object a, object b)
{
foreach (PropertyInfo propA in a.GetType().GetProperties())
{
PropertyInfo propB = b.GetType().GetProperty(propA.Name);
propB.SetValue(b, propA.GetValue(a, null), null);
}
}
如果您將它用於多個對象,那么獲取映射器可能很有用:
public static Action<TIn, TOut> GetMapper<TIn, TOut>()
{
var aProperties = typeof(TIn).GetProperties();
var bType = typeof (TOut);
var result = from aProperty in aProperties
let bProperty = bType.GetProperty(aProperty.Name)
where bProperty != null &&
aProperty.CanRead &&
bProperty.CanWrite
select new {
aGetter = aProperty.GetGetMethod(),
bSetter = bProperty.GetSetMethod()
};
return (a, b) =>
{
foreach (var properties in result)
{
var propertyValue = properties.aGetter.Invoke(a, null);
properties.bSetter.Invoke(b, new[] { propertyValue });
}
};
}
我知道你要求反射代碼,這是一個舊帖子,但我有一個不同的建議,並希望分享它。 它可能比反射更快。
您可以將輸入對象序列化為json字符串,然后反序列化為輸出對象。 具有相同名稱的所有屬性將自動分配給新對象的屬性。
var json = JsonConvert.SerializeObject(a);
var b = JsonConvert.DeserializeObject<T>(json);
嘗試這個:-
PropertyInfo[] aProps = typeof(A).GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Default | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);
PropertyInfo[] bProps = typeof(B).GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Default | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static);
foreach (PropertyInfo pi in aProps)
{
PropertyInfo infoObj = bProps.Where(info => info.Name == pi.Name).First();
if (infoObj != null)
{
infoObj.SetValue(second, pi.GetValue(first, null), null);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.