使用值定义struct数组

Nim*_*oud 3 c#

我可以使用下面的值来定义struct/class数组 - 以及如何?

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

    RemoteDetector oneDetector = new RemoteDetector() { "localhost", 999 };
    RemoteDetector[] remoteDetectors = {new RemoteDetector(){"localhost",999}};        
Run Code Online (Sandbox Code Playgroud)

编辑:我应该在值之前使用变量名称:

    RemoteDetector oneDetector = new RemoteDetector() { Host = "localhost", Port = 999 };
    RemoteDetector[] remoteDetectors = { new RemoteDetector() { Host = "localhost", Port = 999 } };        
Run Code Online (Sandbox Code Playgroud)

Ant*_*ram 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) };
Run Code Online (Sandbox Code Playgroud)