0

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

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

我该怎么办?

4

1 回答 1

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();
        }
}
于 2012-06-28T13:16:25.943 回答