通过设置的GetProperties从一个类属性到另一个 [英] Setting properties from one class to another via GetProperties

查看:136
本文介绍了通过设置的GetProperties从一个类属性到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个简单的例子来清除我的意图。

here is a simple example to clear my intentions.

class A {
    public int Id
    public string Name
    public string Hash
    public C c
}
class B {
    public int id
    public string name
    public C c
}
class C {
    public string name
}
var a = new A() { Id = 123, Name = "something", Hash = "somehash" };
var b = new B();

我想从设置 B 的属性。我曾尝试一些东西,但没有运气。

I want to set b's properties from a. I have tried something but no luck.

public void GenericClassMatcher(object firstModel, object secondModel)
    {
        if (firstModel != null || secondModel != null)
        {
            var firstModelType = firstModel.GetType();
            var secondModelType = secondModel.GetType();
            // to view model
            foreach (PropertyInfo prop in firstModelType.GetProperties())
            {
                var firstModelPropName = prop.Name.ElementAt(0).ToString().ToLower(System.Globalization.CultureInfo.InvariantCulture) + prop.Name.Substring(1); // lowercase first letter
                if (prop.PropertyType.FullName.EndsWith("Model"))
                {
                    GenericClassMatcher(prop, secondModelType.GetProperty(firstModelPropName));
                }
                else
                {
                    var firstModelPropValue = prop.GetValue(firstModel, null);
                    var secondModelProp = secondModelType.GetProperty(firstModelPropName);
                    if (prop.PropertyType.Name == "Guid")
                    {
                        firstModelPropValue = firstModelPropValue.ToString();
                    }
                    secondModelProp.SetValue(secondModel, firstModelPropValue, null);
                }
            }
        }
    }

我该怎么办?

What shall I do?

推荐答案

这听起来像你想的地图的一个类到另一个。 AutoMapper 是我遇到做到这一点的最佳工具。

It sounds like you are trying to map one class to another. AutoMapper is the best tool I've come across to do this.

public class A 
    {
        public int Id;
        public string Name;
        public string Hash;
        public C c;
    }

    public class B 
    {
        public int id;
        public string name;
        public C c;
    }

    public class C 
    {
        public string name;
    }


    class Program
    {
        static void Main(string[] args)
        {
            var a = new A() { Id = 123, Name = "something", Hash = "somehash" };
            var b = new B();

            AutoMapper.Mapper.CreateMap<A, B>();

            b = AutoMapper.Mapper.Map<A, B>(a);


            Console.WriteLine(b.id);
            Console.WriteLine(b.name);

            Console.ReadLine();
        }
}

这篇关于通过设置的GetProperties从一个类属性到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆