2011-03-18 43 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