[英]Initializing complex struct/object in C#
I am working on a project that is using a massive collection of messages in it's communication, in previous projects using C I've worked with these messages as nested arrays of structs 我正在开发一个项目,该项目在通信中使用大量消息,在以前的项目中,我使用C将这些消息作为结构的嵌套数组进行处理
struct message { int value1; int value2; params[] parameters; } struct params { int value3; int value4; } message messageList[2] = { { 1, 2, { 1, 1 }}, { 3, 4, { 2, 2 }}, null } /* not perfect but you get the idea */
I'm trying to do the same in C# but so far I've run into issues at every turn. 我正在尝试在C#中执行相同的操作,但到目前为止,我无处不在。
The end goals: 最终目标:
I thought the best way to do this was similar to C, using structs, but the initialization of C# structs is as messy/complex as initializing objects, and neither would make for an easy to maintain list of all the messages, parameters, etc. 我认为最好的方法类似于使用结构体的C,但是C#结构体的初始化与初始化对象一样混乱/复杂,而且它们都不容易维护所有消息,参数等的列表。
Can anyone help me out here? 有人可以帮我从这里出去吗? Is structs the way to go or is there something else that would be better?
结构是走的路还是还有其他更好的方法?
The C# equivalent of your example would be the following: 您的示例的C#等效项如下:
public class Params
{
public int value3;
public int value4;
}
public class Message
{
public int value1;
public int value2;
public Params[] parameters;
}
Message[] messageList =
{
new Message { value1 = 1, value2 = 2, parameters = new[] { new Params { value3 = 1, value4 = 1 } } },
new Message { value1 = 3, value2 = 4, parameters = new[] { new Params { value3 = 2, value4 = 2 } } }
};
You really should use a class
for this, not a struct
. 您确实应该为此使用
class
,而不是struct
。 This type violates most of the rules for when struct
would be appropriate. 此类型违反了何时使用
struct
大多数规则。
As for initializing - if you used List<T>
, you could use collection initializers to simplify the creation and usage. 至于初始化-如果使用
List<T>
,则可以使用集合初始化程序来简化创建和使用。 Instead of hard coding the initialization in the code, you could parse a file to create the objects on startup. 您可以在启动时解析文件以创建对象,而不是对代码中的初始化进行硬编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.