将对象添加到列表中而不进行声明

时间:2014-01-31 10:52:16

标签: c# .net list oop

这是我要在列表中插入其实例的类。

public class Abc
{
    public int x = 4;      
}

列表是在Program类中创建的。如何在不使用注释行的情况下将数据插入Abc类型列表。

class Program
{
    static void Main(string[] args)
    {
        List<Abc> list = new List<Abc>();
        // abc x = new Abc(); without doing this.

        list.Add(x); //add data to the list of class type abc      
    }
}

2 个答案:

答案 0 :(得分:4)

  

在不创建对象的情况下将类的数据插入列表

没有方法可以添加对象而不创建但是,您可以使用{{1}直接添加没有声明的对象但是你还是要创建对象。

l.Add(new Abc());

您也可以使用collection initializer

class Program
{
    static void Main(string[] args)
    {
        List<Abc> l = new List<Abc>();
        l.Add(new Abc());//add data to the list of class type abc
    }
}

答案 1 :(得分:1)

使用Collection Initializers:

class Program
{
    static void Main(string[] args)
    {
        List<Abc> list = new List<Abc>{ new Abc() };
    }
}

如果您想避免使用new关键字,您需要实现IoC,例如使用工厂:

List<Abc> list = new List<Abc>{ AbcFactory.Get() };

Abc abc = AbcFactory.Get();
List<Abc> list = new List<Abc>{ abc };

更多:

List<Abc> list = new List<Abc>{ new Abc(), new Abc(), new Abc() };

List<Abc> list = new List<Abc>();
list.Add(new Abc());
list.Add(new Abc());
list.Add(new Abc());

Abc abc = new Abc();
List<Abc> list = new List<Abc>{ abc };