【问题标题】:Define struct array with values用值定义结构数组
【发布时间】:2011-03-18 14:10:44
【问题描述】:

我可以用值定义结构/类数组吗 - 如下所示 - 以及如何定义?

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

【问题讨论】:

  • 哦,我忘记了名字:RemoteDetector oneDetector = new RemoteDetector() { Host = "emin", Port = 999 }; RemoteDetector[] remoteDetectors = { new RemoteDetector() { Host = "emin", Port = 999 } };

标签: c#


【解决方案1】:

您可以这样做,但不建议这样做,因为您的结构会是可变的。你应该努力让你的结构保持不变。因此,要设置的值应该通过构造函数传递,这在数组初始化中也很简单。

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

【讨论】:

    【解决方案2】:

    你想像这样使用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# 的语法,但使用结构时的最佳做法是使它们不可变。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-20
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多