gpt4 book ai didi

c# - 用值定义结构数组

转载 作者:行者123 更新时间:2023-11-30 13:41:22 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于c# - 用值定义结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5353185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com