1

我有一个简单的类,它有一些属性,一个属性是一个列表。

public IList<CounterReclaimCardModels> CounterReclaimCards { get; set; }
public long AggID { get; set; }
public string id { get; set; }

我实例化了该类并向其添加了一些数据,但我不知道如何将数据添加到列表中。下面是我如何实例化类

下面是我如何实例化列表并尝试添加到它

 CounterReclaim.CounterReclaimCards = new List<CounterReclaimCardModels>()
        {
            CounterReclaimID = 1,
            ReclaimType = "Rule22Pool",
            ReclaimDisposition = "None",

        };
4

4 回答 4

3

这会将单个类型的项目CounterReclaimCardModels放入一个新列表中:

CounterReclaim.CounterReclaimCards = new List<CounterReclaimCardModels>
    {
        new CounterReclaimCardModels
        {
            CounterReclaimID = 1,
            ReclaimType = "Rule22Pool",
            ReclaimDisposition = "None",
        }
    };
于 2013-09-05T15:12:58.810 回答
2

像这样:

CounterReclaim.CounterReclaimCards = new List<CounterReclaimCardModels>()
{
    new CounterReclaimCardModels()
    {
        CounterReclaimID = 1,
        ReclaimType = "Rule22Pool",
        ReclaimDisposition = "None"
    }

};
于 2013-09-05T15:13:10.060 回答
2

创建列表时,您可以使用以下起始值加载它:

CounterReclaim.CounterReclaimCards = new List<CounterReclaimCardModels>
{
    new CounterReclaimCardModels()
    {
        CounterReclaimID = 1,
        ReclaimType = "Rule22Pool",
        ReclaimDisposition = "None"
    },
    new CounterReclaimCardModels()
    {
        CounterReclaimID = 2,
        ReclaimType = "AwesomeThing",
        ReclaimDisposition = "None"
    },
    variableForAnExistingCounterReclaimCardModels,
    //etc...
};

或者,您可以只使用 Add 方法:

CounterReclaim.CounterReclaimCards = new List<CounterReclaimCardModels>();
CounterReclaim.CounterReclaimCards.Add(new CounterReclaimCardModels()
    {
        CounterReclaimID = 1,
        ReclaimType = "Rule22Pool",
        ReclaimDisposition = "None"
    });

CounterReclaim.CounterReclaimCards.Add(new CounterReclaimCardModels()
    {
        CounterReclaimID = 2,
        ReclaimType = "AwesomeThing",
        ReclaimDisposition = "None"
    });

CounterReclaim.CounterReclaimCards.Add(variableForAnExistingCounterReclaimCardModels);

此外,您可以使用一些值初始化列表,然后使用 Add 稍后添加更多值。

于 2013-09-05T15:26:44.473 回答
1

您必须为列表中的每个项目创建一个实例:

CounterReclaim.CounterReclaimCards = new List<CounterReclaimCardModels>()
{
    new CounterReclaimCardModels
    {
        CounterReclaimID = 1,
        ReclaimType = "Rule22Pool",
        ReclaimDisposition = "None"
    }
    // ...
};
于 2013-09-05T15:13:39.883 回答