通过GetProperties将属性从一个类设置为另一个类

时间:2012-06-28 12:56:35

标签: c# .net

这是一个清除我的意图的简单例子。

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设置a的属性。我尝试过但没有运气。

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

我该怎么办?

1 个答案:

答案 0 :(得分:1)

听起来你正试图一个类映射到另一个类。 AutoMapper是我遇到的最好的工具。

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