2013-01-12 20 views
-5

我有以下問題。我如何在c#中創建一個對象數組?我正在考慮這種做法有什麼我通常使用PHP:C#如何創建一個對象數組?

$obj1 = new stdClass(); 
$obj1->first = "first-str"; 

$obj2 = new stdClass(); 
$obj2->second = "second-str"; 

$objarray = array(); 

$objarray['first'] = $obj1; 
$objarray['second'] = $obj2; 

echo $objarray['second']->second; 
+2

Stackoverflow不是代碼轉換器。請閱讀[常見問題]和[問] –

+1

[數組(C#編程指南)](http://msdn.microsoft.com/en-us/library/9b9dty7d.aspx)。請享用。 – Oded

+0

爲什麼你的示例代碼都是PHP的? –

回答

0

From MSDN:

string[] names = new string[3] {"Matt", "Joanne", "Robert"}; 

names[1] == "Joanne" 

從你的例子,也許你想創建Dictionary

Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
dictionary.Add("first", "first-str"); 
dictionary.Add("second", "second-str"); 

dictionary["first"] == "first-str" 
+0

但是有沒有簡單的方法來存儲對象並訪問它?如果dictionary [「first」]有一個對象,我怎樣才能訪問它的屬性? – vivask

+0

泛型字典顯示按類型存儲的對象的屬性。在當前的例子中,'dictionary [「first」]'會公開'String'的所有屬性,比如'.Lenght'等。如果你想用你的特定對象定義字典,例如'Dictionary ', 'dictionary [「first」]'會暴露'SomeObject'的接口。 – Algirdas

0

您可以使用List類可以使用LINQ庫也擴展變得更加查詢/ PHP如果你想等。首先,實例化一個列表:

List<Object> objects = new List<Object>(); 

的,以填補它,你必須將對象添加到它:

objects.Add(obj1); 
objects.Add(obj2); 
... 

然後你就可以訪問對象實例,像這樣:

// First object: 
Object objFirst = objects[0]; 
// Second object: 
Object objSecond = objects[1]; 

或者使用Linq First(),Last()等......當然,要使用這些函數(here一個完整列表),必須將System.Linq添加到源文件頂部的使用指令中,並確保你在參考System.Core庫在您的項目中。

相關問題