初始化对象不在列表中的&LT工作; T> [英] Object initializers not working in List<T>

查看:113
本文介绍了初始化对象不在列表中的&LT工作; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

        List<Car> oUpdateCar = new List<Car>();

        oUpdateCar.Add(new Car());
        oUpdateCar[0].name = "Color";
        oUpdateCar[0].value = "red";

        oUpdateCar.Add(new Car());
        oUpdateCar[1].name = "Speed";
        oUpdateCar[1].value = "200";

上面的代码工作,但我想初始化它,当我创建列表如下,

The above code is working but i want to initialize it when i create the list as below,

List<Car> oUpdateCar = new List<Car>
    {

        new Car{
        name = "Color";
        value = "red";}

    new Car{
        name = "Speed";
        value = "200";}
    }



上面的代码是不是加工。我在想什么。我使用C#.NET 2.0。请帮忙

The above code is not working. What am i missing. I am using c# .NET 2.0. Please help.

推荐答案

收集和对象初始化是新的C#3.0;它们不能在Visual Studio 2005中使用

Collection and object initializers are new to C# 3.0; they cannot be used in Visual Studio 2005.

此外,这是无效的语法甚至在C#3;您需要更换分号(; )用逗号()的对象初始化器内,并添加之间的逗号每个对象的集合初始化。

Also, that's invalid syntax even in C# 3; you need to replace the semicolons (;) with commas (,) inside the object initializers, and add a comma between each object in the collection initializer.

这篇关于初始化对象不在列表中的&LT工作; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆