开发者

Define struct array with values

开发者 https://www.devze.com 2023-02-18 19:04 出处:网络
Can I define struct/class array with values -like below- and how? struct RemoteDetector { public string Host;

Can I define struct/class array with values -like below- and how?

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

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

Edit: I should use variable 开发者_JAVA技巧names before the values:

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


You can do that, but it is not recommended as your struct would be mutable. You should strive for immutability with your structs. As such, values to set should be passed through a constructor, which is also simple enough to do in an array initialization.

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


You want to use C#'s object and collection initializer syntax like this:

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

Edit: It's really important that you follow Anthony's advice and make this struct immutable. I am showing some of C#'s syntax here but the best practice when using structs is to make them immutable.

0

精彩评论

暂无评论...
验证码 换一张
取 消