将对象转换为其他对象

本文关键字:对象 其他 转换 | 更新日期: 2023-09-27 18:29:34

我有一个类,它是我引用的程序集的一部分。我想转换该类型的对象到我自己的类,它实现了我引用的类

假设我的推荐人有

public class customer
{
public string name {get;set}
public string address{get;set}
}

我创建了

public class mycustomer : customer
{
 public string name {get; set}
 public string address{get;set}
 public string email {get;set}
}

如何将客户转换为我的客户并返回我读过关于使用反射的文章,但我对它还不够适应,无法亲自写出来。

PS。请停止使用命名约定语义-这是一个粗略的动态理论示例(此处不涉及命名约定,仅在实际代码中)提前感谢

编辑:我发现我无论如何都做不到。我需要序列化一个没有serializable属性的对象,我想我可以镜像该类并使其可序列化,但我刚刚意识到这个类中的一些属性没有serialized属性。

不管怎样,谢谢——我会把这个问题的最佳答案标记为答案/Alex

将对象转换为其他对象

Automapper可以帮助您。

或者,如果你只有一个类,那么写一个自己的类是相当简单的。

private mycustomer(customer c)
{
    return new mycustomer { name = c.Name, address = c.address,email = c.email };
}

然而,您不应该认为不需要继承来映射

public class mycustomer : customer

应该是

public class mycustomer

您还应该使用此命名约定

public class MyCustomer
{
   public string Name {get; set}
   public string Address{get;set}
   public string Email {get;set}
}

mycustomer已经有从customer继承的成员。不要隐藏那些成员:

public class customer
{
    public string name { get; set; }
    public string address { get; set; }
}
public class mycustomer : customer
{ 
    // name and address are inherited
    public string email { get; set; }
}

现在mycustomercustomer,并且这种转换没有问题——只需将mycustomer的实例分配给customer类型的变量:

mycustomer mc = new mycustomer();
customer c = mc;

将它们转换回来很奇怪,因此customer没有email属性,它也不会出现——您仍然只有基本类型提供的数据,所以只需在这里使用基本类型。但是,如果客户实际上是一个mycustomer实例(请参阅上面的代码),那么您只需要铸造:

mycustomer mc2 = (mycustomer)c;

BTW在C#中,我们使用PascalNaming作为类型名和公共成员。

无需自己编写。您可以使用以下通用算法使用反射将Customer的属性复制到MyCustomer对象:

    public B Convert<A, B>(A element) where B : A, new()
    {
        //get the interface's properties that implement both a getter and a setter
        IEnumerable<PropertyInfo> properties = typeof(A)
            .GetProperties()
            .Where(property => property.CanRead && property.CanWrite).ToList();
        //create new object
        B b = new B();
        //copy the property values to the new object
        foreach (var property in properties)
        {
            //read value
            object value = property.GetValue(element);
            //set value
            property.SetValue(b, value);
        }
        return b;
    }

我认为只在一个场景中使用像AutoMapper这样的完整库有点过头了。

简单的方法!

public class ClassA
    {
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }
        public string note { get; set; }
    }
 public class ClassB
    {
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }
        public string note { get; set; }
        public int index { get; set; }
    }
static void Main(string[] args)
        {
           //create an object with ClassA  type
            ClassA a = new ClassA { id=1,age=12,name="John",note="good"};
            ClassB b=a.Cast<ClassB>();
        }

"铸造"方法实现如下视频https://www.youtube.com/watch?v=XUqfg9albdA