C# 将类属性和值从一个类动态映射到另一个类

C# 将类属性和值从一个类动态映射到另一个类,c#,class,dynamic,C#,Class,Dynamic,我有一个类名Invoice,但这个类是我无法控制的 因为它来自另一家公司的API,我们保存发票 public class InvoiceOutput { public string InvoiceNum {get; set;} public string TotalAmount {get; set;} public string Date {get; set;} public string Address{get; set;} public List&l

我有一个类名Invoice,但这个类是我无法控制的 因为它来自另一家公司的API,我们保存发票

public class InvoiceOutput
{
    public string InvoiceNum {get; set;}
    public string TotalAmount {get; set;}
    public string Date {get; set;}
    public string Address{get; set;}

    public List<InvoiceRows> {get; set;}

    public Add() 
    { 
          //invoice Add functionality
    }
    public bool Save() 
    { 
           //invoice Save functionality
    }


//This is my own Invoice, a copy from all writable properties of InvoiceOutput
public class InvoiceInput
{
    public string InvoiceNum {get; set;}
    public string TotalAmount {get; set;}
    public string Date {get; set;}
    public string Address{get; set;}

    public List<InvoiceRows> {get; set;}
}
我怎样才能做到现在这样: 假设我把它放在for循环下。 记住,我的xml是动态的,所以它取决于有什么属性 所以它被分配到这里

for(int i=0;i<InvoiceOutput.Count; i++)
{
InvoiceOutput.Add();
InvoiceOutput.InvoiceNum  = InvoiceInput[i].InvoiceNum;
InvoiceOutput.TotalAmount = InvoiceInput[i].TotalAmount;
InvoiceOutput.Save();
}

for(int i=0;i我假设您希望将所有属性的值从类
InvoiceOutput
对象复制到
InvoiceInput
对象。 然后尝试基于反射的方式

    private static object CloneObject(object o)
    {
        Type t = o.GetType();
        PropertyInfo[] properties = t.GetProperties();

        object p = new InvoiceInput();

        foreach (PropertyInfo pi in properties)
        {
            p.GetType().GetProperty(pi.Name).SetValue(p, pi.GetValue(o, null),null);
        }

        return p;
    }
这里我假设这两个类的属性名称相同

然后,您可以将其用作

  InvoiceInput b = (InvoiceInput)CloneObject(outp);
如果您要经常使用它,那么您可以尝试将其写入。然后您可以像这样克隆所有对象

  inputObject.CloneOutputObject(ouputObject);

更新

您可以使用-它允许您使用任何IConvertible类型的运行时信息来更改表示格式。但是,并非所有转换都是可能的,如果您希望支持来自不IConvertible类型的转换,则可能需要编写特殊情况逻辑

      p.GetType().GetProperty(pi.Name).SetValue(p, Convert.ChangeType(pi.GetValue(o, null),YourTypeToConvertTo)),null);
要获取目标属性类型,可以执行以下操作

      PropertyInfo newp = typeof(InvoiceInput).GetProperties().where(x=>x.Name == pi.Name).FirstOrDefault();
然后在设置值时

      p.GetType().GetProperty(pi.Name).SetValue(p, Convert.ChangeType(pi.GetValue(o, null),newp.PropertyType)),null);
你可以用它。 例如,要使用:

//初始化一次

Mapper.CreateMap<InvoiceInput, InvoiceOutput>();
Mapper.CreateMap<InvoiceOutput, InvoiceInput>();
Mapper.CreateMap();
CreateMap();
//使用

InvoiceInput invoiceInput = Mapper.Map<InvoiceInput>(invoiceOutput);
InvoiceInput InvoiceInput=Mapper.Map(invoiceOutput);
非常感谢!:-)我将尝试这种方法。是的,两个类具有相同的属性名称。如果变量类型不同呢?。
Mapper.CreateMap<InvoiceInput, InvoiceOutput>();
Mapper.CreateMap<InvoiceOutput, InvoiceInput>();
InvoiceInput invoiceInput = Mapper.Map<InvoiceInput>(invoiceOutput);