我正在編寫一個應用程序來處理WMI對象。我有一個Computer
類與一個List<Component>
財產,是Component
abtract基類,從中得到所有派生類,如Monitor
,ComputerUnit
,Printer
等。如何創建派生類的嵌套列表
考慮到種類繁多的WMI對象,我決定使用自定義.NET泛型的第一次(我是初學者)的,這是代碼 - 只是相關線路:
public class Computer
{
public List<Component> ListOfComponents { get; set; }
}
public class Component
{
public NameSpaceBase[] WMI_ClassArray { get; set; }
}
public class Monitor : Component
{ }
public class ComputerUnit : Component
{ }
public static void Main()
{
Computer computer = new Computer(hostName);
Monitor monitor = computer.Get<Monitor>(new NameSpaceBase[] {
new WMI_Monitor() });
ComputerUnit computerUnit = computer.Get<ComputerUnit>(
new NameSpaceBase[] {
new WMI_Bios(),
new WMI_ComputerSystem() });
computer.ListOfComponents.Add(monitor);
computer.ListOfComponents.Add(computerUnit);
}
這是工作的罰款,直到我意識到我想對待每一個組件作爲列表本身,因爲我需要有多個顯示器和/或分離等多種設備,因此我適時改變我的屬性和方法:
public class Computer
{
public List<List<Component>> ListOfComponents { get; set; }
}
public static void Main()
{
Computer computer = new Computer(hostName);
List<Monitor> monitor = computer.Get<Monitor>(new NameSpaceBase[] {
new WMI_Monitor() });
List<ComputerUnit> computerUnit = computer.Get<ComputerUnit>(
new NameSpaceBase[] {
new WMI_Bios(),
new WMI_ComputerSystem() });
computer.ListOfComponents.Add(monitor);
computer.ListOfComponents.Add(computerUnit);
}
但現在我在la給了error CS1503: Argument 1: cannot convert from 'System.Collections.Generic.List<Machine.Components.Monitor>' to 'System.Collections.Generic.List<Machine.Components.Component>'
兩條線。
我不明白錯誤在哪裏,因爲如果我評論最後兩行,我可以看到List和List對象是正確創建的,正確的類型並填充了預期的數據。故事的
底線:我不明白爲什麼我不能添加一個List<Monitor>
對象爲List<List<Component>>
,而我可以一個Monitor
對象添加到List<Component>
。
這與協方差有關,但我不確定爲什麼它不起作用,因爲列表是協變的。 –
@ rory.ap,因爲協方差僅與接口和委託相關 –
@ rory.ap,不支持類中的協方差 – Rahul