使用值定义struct数组

时间:2011-03-18 14:10:45

标签: c#

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

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

2 个答案:

答案 0 :(得分: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) };

答案 1 :(得分: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#的语法,但使用结构时的最佳实践是使它们不可变。