2014-01-31 35 views
-3

這是我希望在列表中插入其實例的類。在不聲明的情況下將對象添加到列表中

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  
    } 
} 
+1

目的是什麼? –

回答

4

插入數據

沒有向其添加對象沒有雖然創建方式,你可以直接添加對象而不聲明,使用l.Add(new Abc());但無論如何您必須創建對象。

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

您也可以使用collection initializer

List<Abc> l = new List<Abc>({new Abc(), new Abc()}); 
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 }; 
相關問題