列表包含无效参数

时间:2016-11-18 09:19:54

标签: c# list object

我有以下课程:

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; }
}

我正在创建List并分配属性值,但是当我添加列表时,我收到错误:

  

最佳重载方法匹配   &#39; System.Collections.Generic.List.Add(精选)&#39;有一些   无效的参数

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);

我错过了什么吗?

3 个答案:

答案 0 :(得分:1)

您正在将列表添加到另一个列表中。您想要添加列表项。

而不是

productSelections.selection.Add(listOfProductSelections);

productSelections.selection.AddRange(listOfProductSelections);

但您必须确保此时已初始化selection属性,否则您将遇到NullReferenceException

顺便说一下,检查所有您的错误消息。您将看到第二条消息,告诉您哪种类型被排除以及您正在使用哪种类型。

答案 1 :(得分:0)

您应该使用AddRange,因为listOfProductSelections是一个列表。

productSelections.selection.AddRange(listOfProductSelections)

答案 2 :(得分:0)

productSelections.selection是对List的引用,当您尝试向其添加项时(示例的最后一行), Add 方法需要选择类型的参数 - 您正在传递 listOfProductSelections ,这是对另一个列表的引用。

也许您想要添加所需类型的 dataSelection ?如果没有,您可以像其他受访者建议的那样使用 AddRange