简体   繁体   English

相同的变量名称 - 2个不同的类 - 如何将值从一个复制到另一个 - 反射 - C#

[英]Same Variable Names - 2 Different Classes - How To Copy Values From One To Another - Reflection - C#

Without using AutoMapper... (because someone in charge of this project will shit bricks when they see dependencies) 没有使用AutoMapper ...(因为当他们看到依赖项时,负责这个项目的人会打砖块)

I have a class (class A) with however many properties. 我有一个类(A类),但有很多属性。 I have another class (class B) with those same properties (same names and type). 我有另一个类(B类)具有相同的属性(相同的名称和类型)。 Class B could also have other un related variables. B类也可能有其他无关的变量。

Is there some simple reflection code that can copy values from class A to class B? 是否有一些简单的反射代码可以将值从A类复制到B类?

The simpler the better. 越简单越好。

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

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

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

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. 您可以将输入对象序列化为json字符串,然后反序列化为输出对象。 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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将属性从一个 object 复制到另一个具有不同值 C# - how to copy properties from one object to another with different values C# 如何使用来自不同类的变量值 WPF C# - How to use variable values from different classes WPF C# 如何动态地通过C#中的反射从派生类中获取值? - How to get values from derived classes by reflection in C# dynamically? C# - 将属性值从一个实例复制到另一个实例,不同的类 - C# - copying property values from one instance to another, different classes 如何使用反射将具有集合的复杂类复制到其他类和不同的专有名称 - How to use reflection to copy complex classes with collections to other classes and different proper names 在C#中将值从一个businesobject复制到另一个而没有循环 - Copy values from one businesobject to another without loop in c# 如何使用C#中的WinSCP .NET程序集将内容从一个远程目录复制到同一服务器中的另一个目录 - How to copy things from one remote directory to another in the same server using WinSCP .NET assembly in C# 如何在C#中的同一数据表中将数据从一列复制到另一列 - How to copy data from one column to another at the same datatable in c# C#代码用于处理具有相同方法名称的不同类 - C# code to handle different classes with same method names 将数据从一个类实例复制到另一个具有相同属性名称但不同属性类型的类实例 - Copy data from one class instance to another class instance having same property names but different property types
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM