我有以下课程:
public class OrderArticlesAdapter : RecyclerView.Adapter
{
public List<OrderArticleViewModel> listOfOrderArticles;
.....
.....
//constructor
public OrderArticlesAdapter(List<OrderArticleViewModel> orderArticles, ....., .....)
{
listOfOrderArticles = orderArticles;
......
}
}
我希望该类不仅能够与OrderArticleViewModel
的列表一起使用,而且还能够与类型Invoices
的列表和任何其他类型一起使用。 OrderArticleViewModel
类看起来像这样:
public class OrderArticleViewModel
{
public string ArticleId { get; set; }
public string LotId { get; set; }
public string ArticleName { get; set; }
public string PriceDiscount { get; set; }
public string ArticlePrice { get; set; }
public string ArticleQuantity { get; set; }
public string ArticleTotalPrice { get; set; }
public string Barcode { get; set; }
public string ExpireDate { get; set; }
public string LotName { get; set; }
public string ArticlePriceAfterDiscount
{
get
{
decimal priceDiscount;
if (!Decimal.TryParse(PriceDiscount, out priceDiscount))
{
priceDiscount = 0;
}
decimal articlePrice = Convert.ToDecimal(ArticlePrice);
decimal discountAmount = Math.Round(articlePrice * (priceDiscount / 100), 4);
decimal articlePriceAfterDiscount = articlePrice - discountAmount;
return articlePriceAfterDiscount.ToString();
}
}
}
Invoices
类如下:
public class Invoices
{
public string ArtId { get; set; }
public string Name { get; set; }
public string Quantity { get; set; }
public string Price { get; set; }
public string Sum { get; set; }
public string Discount { get; set; }
public string PriceWodiscount { get; set; }
public string Id { get; set; }
}
ArticleId
,ArticleName
,ArticleQuantity
,PriceDiscount
,ArticlePrice
,Discount
,ArticlePriceAfterDiscount
来自类别{{1} }对应于类OrderArticleViewModel
中的属性ArtId
,Name
,Quantity
,Discount
,Price
,Sum
。如何使Invoices
构造函数能够接收OrderArticlesAdapter
或OrderArticleViewModel
或任何其他类型的通用列表,而又不会破坏我已经使用过{{1 }}?
答案 0 :(得分:3)
创建另一个构造函数,在其中将发票列表转换为ArticleViewModel列表:
public class OrderArticlesAdapter : RecyclerView.Adapter
{
public List<OrderArticleViewModel> listOfOrderArticles;
public OrderArticlesAdapter(List<OrderArticleViewModel> orderArticles, ....., .....)
{
listOfOrderArticles = orderArticles;
}
public OrderArticlesAdapter(List<Invoice> invoices)
{
listOfOrderArticles = invoices.Select(MapToArticleVM).ToList();
}
private OrderArticleViewModel MapToArticleVM(Invoice invoice)
{
return new OrderArticleViewModel
{
ArticleId = invoice.ArtId,
// ...
};
}
}
请注意,结果列表将缺少某些属性,例如,Invoice
不包含Barcode
。
答案 1 :(得分:2)
一种选择是编写扩展方法以将发票转换为视图模型
public static class InvoicesExtensions
{
public static OrderArticleViewModel ToOrderArticleViewModel(this Invoices i)
{
return new OrderArticleViewModel { ArticleId = i.ArtId, ... };
}
}
...然后您可以像这样调用构造函数
var invoices = new List<Invoices>();
var adapter = new OrderArticlesAdapter(invoices.Select(i => i.ToOrderArticleViewModel()).ToList());
我也会推荐
Invoices
重命名为Invoice
,因为它似乎代表实际的发票而不是多张发票IEnumerable<OrderArticleViewModel>
代替List<OrderArticleViewModel>
作为构造函数参数,因为这使构造函数更具通用性