C# 在没有声明的情况下将对象添加到列表中

C# 在没有声明的情况下将对象添加到列表中,c#,.net,list,oop,C#,.net,List,Oop,这是我要在列表中插入其实例的类 public class Abc { public int x = 4; } 列表是在程序类中列出的。如何在不使用注释行的情况下将数据插入到Abc类型的列表中 class Program { static void Main(string[] args) { List<Abc> list = new List<Abc>(); // abc x = new Abc(); w

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

public class Abc
{
    public int x = 4;      
}
列表是在程序类中列出的。如何在不使用注释行的情况下将数据插入到
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      
    }
}
类程序
{
静态void Main(字符串[]参数)
{
列表=新列表();
//abc x=新abc();不执行此操作。
list.Add(x);//将数据添加到abc类类型的列表中
}
}
将类的数据插入列表而不创建对象

虽然可以使用
l.add(new Abc())直接添加对象,而无需声明,但有no方法可以在不创建对象的情况下添加对象但无论如何都必须创建对象

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
    }
}
类程序
{
静态void Main(字符串[]参数)
{
也请列出

List l=新列表({new Abc(),new Abc()});
使用

类程序
{
静态void Main(字符串[]参数)
{
List List=新列表{new Abc()};
}
}
如果要避免使用new关键字,则需要实现IoC,例如使用工厂:

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

Abc abc = AbcFactory.Get();
List<Abc> list = new List<Abc>{ abc };
List List=newlist{AbcFactory.Get()};
Abc=AbcFactory.Get();
列表=新列表{abc};
更多:

List List=newlist{new Abc(),new Abc(),new Abc()};
列表=新列表();
添加(新的Abc());
添加(新的Abc());
添加(新的Abc());
Abc=新Abc();
列表=新列表{abc};
class Program
{
    static void Main(string[] args)
    {
        List<Abc> list = new List<Abc>{ new Abc() };
    }
}
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 };