Named variable names - 2 different classes - How to copy values ​​from one to another - Reflection - C #

Without using AutoMapper ... (because someone who is responsible for this project will pull bricks when they see the dependencies)

I have a class (class A) with any set of properties. I have another class (class B) with the same properties (same names and type). Class B may also have other unrelated variables.

Is there some simple reflection code that can copy values ​​from class A to class B?

The simpler the better.

+6
source share
5 answers
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); } 
+21
source

It?

 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); } } 
+4
source

If you will use it for more than one object, it may be useful to get a cartographer:

 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 }); } }; } 
+1
source

Try the following: -

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

I know that you asked for the reflection code, and this is an old post, but I have another suggestion and I want to share it. It can be faster than reflection.

You can serialize the input object to a json string, and then deserialize the output object. All properties with the same name are automatically assigned to the new properties of the object.

 var json = JsonConvert.SerializeObject(a); var b = JsonConvert.DeserializeObject<T>(json); 
0
source

Source: https://habr.com/ru/post/888586/


All Articles