Same Variable Names - 2 Different Classes - How To

2020-06-18 02:53发布

问题:

Without using AutoMapper... (because someone in charge of this project will shit bricks when they see dependencies)

I have a class (class A) with however many properties. I have another class (class B) with those same properties (same names and type). Class B could also have other un related variables.

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

The simpler the better.

回答1:

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


回答2:

This?

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


回答3:

If you will use it for more than one object then it may be useful to get mapper:

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


回答4:

Try this:-

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


回答5:

I know you asked for reflection code and It's an old post but I have a different suggestion and wanted to share it. It could be more faster than reflection.

You can serialize the input object to json string, then deserialize to output object. All the properties with same name will assign to new object's properties automatically.

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