2011-03-18 38 views
3

我可以使用如下的值定義結構/類數組嗎?以及如何?使用值定義結構數組

struct RemoteDetector 
    { 
     public string Host; 
     public int Port; 
    } 

    RemoteDetector oneDetector = new RemoteDetector() { "localhost", 999 }; 
    RemoteDetector[] remoteDetectors = {new RemoteDetector(){"localhost",999}};   

編輯:

RemoteDetector oneDetector = new RemoteDetector() { Host = "localhost", Port = 999 }; 
    RemoteDetector[] remoteDetectors = { new RemoteDetector() { Host = "localhost", Port = 999 } };   
+0

[初始化結構體在C#數組(http://stackoverflow.com/questions/309496/initializing-an-array-of-structs-in-c)的可能的複製 – 2011-03-18 14:14:49

+0

喔我已經忘記名稱: RemoteDetector oneDetector = new RemoteDetector(){Host =「emin」,Port = 999}; RemoteDetector [] remoteDetectors = {new RemoteDetector(){Host =「emin」,Port = 999}}; – 2011-03-18 14:15:26

+0

C#不是JavaScript – 2011-03-18 14:16:39

回答

7

你可以這樣做,但不推薦使用它,因爲你的結構是可變的。你應該努力爭取與你的結構不變。因此,要設置的值應該通過構造函數傳遞,該構造函數在數組初始化中也足夠簡單。

struct Foo 
{ 
    public int Bar { get; private set; } 
    public int Baz { get; private set; } 

    public Foo(int bar, int baz) : this() 
    { 
     Bar = bar; 
     Baz = baz; 
    } 
} 

... 

Foo[] foos = new Foo[] { new Foo(1,2), new Foo(3,4) }; 
+3

+1結構*應該是不可變的。 – 2011-03-18 14:16:05

3

你想用C#'s object and collection initializer syntax這樣的:我的價值觀之前,應使用變量名

struct RemoteDetector 
{ 
    public string Host; 
    public int Port; 
} 

class Program 
{ 
    static void Main() 
    { 
     var oneDetector = new RemoteDetector 
     { 
      Host = "localhost", 
      Port = 999 
     }; 

     var remoteDetectors = new[] 
     { 
      new RemoteDetector 
      { 
       Host = "localhost", 
       Port = 999 
      } 
     }; 
    } 
} 

編輯:這是非常重要的,你跟隨Anthony's advice並使該結構不可變。我在這裏展示了一些C#的語法,但使用結構時的最佳做法是使它們不可變。

+0

我問過最簡單的版本,謝謝! – 2011-03-18 14:18:28