2016-11-18 122 views
-2

我有以下類:列表具有無效的參數

public class Selections 
{ 
    public List<Selection> selection { get; set; } 
} 

public class Selection 
{ 
    public Promotion promotion { get; set; } 
    public Products products { get; set; } 
} 

public class Products 
{ 
    public List<int> productId { get; set; } 
} 

我創建列表和分配屬性值,但是當我加入列表我收到提示:

The best overloaded method match for 'System.Collections.Generic.List.Add(Selection)' has some invalid arguments

C#代碼:

Selections productSelections = new Selections(); 
List<Selection> listOfProductSelections = new List<Selection>(); 
Selection dataSelection = new Selection() 
{ 
    promotion = new ProviderModels.Common.Promotion() 
    { 
     promotionID = Convert.ToInt32(applicablePromotion.PromotionId), 
     lineOfBusiness = applicablePromotion.LineOfBusiness 
    }, 
    products = new ProviderModels.Common.Products() 
    { 
     productId = GetIdsOfSelectedProducts(context, selectedOffer) 
    } 
}; 
productSelections.selection.Add(listOfProductSelections); 

我錯過了什麼嗎?

回答

1

要添加列表到另一個列表。你想添加列表項。

而不是

productSelections.selection.Add(listOfProductSelections); 

productSelections.selection.AddRange(listOfProductSelections); 

但你必須確保你已經初始化,在這一點上selection屬性,否則你會碰到一個NullReferenceException

順便說一句,檢查所有你的錯誤消息。您會看到第二條消息,告訴您哪種類型被察覺以及您正在使用什麼。

+0

確定。但在此之前,我還必須添加'listOfProductSelections.Add(dataSelection)'。對?另外,雖然我初始化'選擇dataSelection =新選擇()' –

+0

在上面的代碼中調用''AddRange'on productSelections.selection'我碰上空引用異常。如果該屬性未初始化,則它將爲'null'。所以你會遇到異常。 – Sefe

0

你應該使用AddRange作爲listOfProductSelections是一個列表。

productSelections.selection.AddRange(listOfProductSelections) 
0

productSelections.selection是一個列表的引用,consquently當您嘗試將項目添加到它(例如你的最後一行)的添加方法期望類型選擇的一個參數 - 你「重新傳遞listOfProductSelections這是另一個列表的引用。

也許你想添加dataSelection哪些是必需的類型?如果沒有,您可以使用AddRange,如其他受訪者所建議。