我有一個叫Product
的抽象類,叫做DifferentProduct
的另一個類和一個叫IProduct
的接口。隱式類型轉換不起作用
類別Product
和類別DifferentProduct
均來自名爲IProduct
的接口。
public class Product : IProduct
{
public int ID { get; set; }
public string ProductName { get; set; }
}
public class DifferentProduct : IProduct
{
public int ID { get; set; }
}
public interface IProduct
{
int ID { get; set; }
}
我有功能,即我傳遞
ProductListing(List<IProduct>, List<IProduct>)
{
}
現在試圖調用函數從一些文件
List<Product> productList1;
List<DifferentProduct> differentProductList;
XYZ.ProductListing(productList1, differentProductList);
我在上面一行得到以下錯誤
錯誤CS1503:參數1無法從012轉換'System.Collections.Generic.List' 到 'System.Collections.Generic.List'
錯誤CS1503:參數2無法從System.Collections.Generic.List轉換爲 System.Collections.Generic.List
有沒有什麼辦法可以解決這個解決方案沒有明確的類型轉換? 我需要工作,沒有明確的類型轉換。
閱讀有關協變和逆變。 https://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx – Andrew
此問題肯定是一些共同/反差異問題的副本 –
蘋果列表不是列表水果。您可以將桔子添加到水果列表中,但您的蘋果列表不能接受該列表。 DifferentProduct的列表是相同的。使用產品列表的人可能希望能夠將Widget添加到列表中,但是您只給予(或者試圖給予)其可以接受DifferentProduct的列表。 –