将 string[] 数组字段分配给另一个相同类型的数组字段 c#
Assign string[] array field to another array field of same type c#
我的解决方案中定义了两个 classes
public class Registration {
[...]
public list<Account> Accounts {get; set;}
}
public class Account {
[...]
public string Code { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
在我使用的 Web 服务中,以下 class 定义可用
public partial class VendReg {
[...]
private Payment_Details[] requestDetailsField;
[System.Xml.Serialization.XmlArrayItemAttribute(IsNullable=false)]
public Payment_Details[] RequestDetails {
get {
return this.requestDetailsField;
}
set {
this.requestDetailsField = value;
}
}
}
public partial class Payment_Details {
private string bk_CodeField;
private string bk_NameField;
private string bk_AddressField;
public string Bk_Code {
get {
return this.bk_CodeField;
}
set {
this.bk_CodeField = value;
}
}
public string Bk_Name {
get {
return this.bk_NameField;
}
set {
this.bk_NameField = value;
}
}
public string Bk_Address {
get {
return this.bk_AddressField;
}
set {
this.bk_AddressField = value;
}
}
}
我想将帐户分配给 Payment_Details 数组的请求详细信息。我在下面尝试了这段代码
vendReg.RequestDetails = registration.Accounts.Cast<Payment_Details>().ToArray();
I got invalid cast exception: Unable to cast object of type 'Account' to type 'Payment_Details'
请指导我做错了什么
你需要自己转换这个(或者你可以看看 Automapper 之类的东西)
vendReg.RequestDetails = registration.Accounts.Select(acc =>
new Payment_Details {
Bk_Code = acc.Code,
Bk_Name = acc.Name,
Bk_Address = acc.Address
}).ToArray();
我的解决方案中定义了两个 classes
public class Registration {
[...]
public list<Account> Accounts {get; set;}
}
public class Account {
[...]
public string Code { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
在我使用的 Web 服务中,以下 class 定义可用
public partial class VendReg {
[...]
private Payment_Details[] requestDetailsField;
[System.Xml.Serialization.XmlArrayItemAttribute(IsNullable=false)]
public Payment_Details[] RequestDetails {
get {
return this.requestDetailsField;
}
set {
this.requestDetailsField = value;
}
}
}
public partial class Payment_Details {
private string bk_CodeField;
private string bk_NameField;
private string bk_AddressField;
public string Bk_Code {
get {
return this.bk_CodeField;
}
set {
this.bk_CodeField = value;
}
}
public string Bk_Name {
get {
return this.bk_NameField;
}
set {
this.bk_NameField = value;
}
}
public string Bk_Address {
get {
return this.bk_AddressField;
}
set {
this.bk_AddressField = value;
}
}
}
我想将帐户分配给 Payment_Details 数组的请求详细信息。我在下面尝试了这段代码
vendReg.RequestDetails = registration.Accounts.Cast<Payment_Details>().ToArray();
I got invalid cast exception: Unable to cast object of type 'Account' to type 'Payment_Details'
请指导我做错了什么
你需要自己转换这个(或者你可以看看 Automapper 之类的东西)
vendReg.RequestDetails = registration.Accounts.Select(acc =>
new Payment_Details {
Bk_Code = acc.Code,
Bk_Name = acc.Name,
Bk_Address = acc.Address
}).ToArray();