简体   繁体   English

在C#中初始化复杂的结构/对象

[英]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: 最终目标:

  • One large file with all the message definitions, these must be: 一个包含所有消息定义的大文件,这些文件必须是:
    • Organized/Readable (someone reviewing definitions should understand what is going on) 有组织/可读(检查定义的人应该了解发生了什么)
    • Compact (100 messages shouldn't take 10,000 LOC) 紧凑(100条消息不应占用10,000 LOC)
    • Flexible (array lengths) 灵活(数组长度)
  • Message definitions are parsed into an array of objects with nested objects 消息定义被解析为带有嵌套对象的对象数组
    • Parsing/initialization needn't be super fast, only happens on startup on a PC 解析/初始化不必太快,只需在PC上启动时进行
  • Bonus the resulting list of objects is immutable. 另外 ,对象的结果列表是不可变的。 (forgot to mention this first round) (忘了第一轮)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM