如何填充结构数组,而无需为每个成员使用一行代码? [英] How to populate array of structs, without using a line for code for each member?

查看:70
本文介绍了如何填充结构数组,而无需为每个成员使用一行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试寻找一种更好的方法来填充一系列结构。
首先,这是用于制作我的结构的数据

I'm currently trying to find a better way to populate an array of structs. first off, this is the data going in to making my struct

enum DataType
{
    Uint8, Uint16, Byte, Int16, Int32,
    TypeSatInfo, TypeCell, ByteArray
}
enum ReadWriteState
{
    ReadWrite, ReadOnly, WriteOnly
}
struct Parameter
{
   public string ParamName;
   public short ParamId;
   public  DataType Datatype;
   public ReadWriteState ReadWrite;

}

然后,我有一个应该容纳填充数组的类

Then I have a class which should hold my populated array

static class Parameters
{
    public static Parameter[] Param = new Parameter[80];
}

最后一部分是该函数,我想使用该函数

and the last part I have is the function, which I want to use to populate the array.

void populateParameters()
{
    Parameters.Param[0].ParamName = "RevProtocol";
    Parameters.Param[0].ParamId = 0x0001;
    Parameters.Param[0].Datatype = DataType.Uint16;
    Parameters.Param[0].ReadWrite = ReadWriteState.ReadOnly;

    Parameters.Param[1].ParamName = "HwProtocol";
    Parameters.Param[1].ParamId = 0x0002;
    Parameters.Param[1].Datatype = DataType.Uint16;
    Parameters.Param[1].ReadWrite = ReadWriteState.ReadOnly;

    //keep this going until array is full.
}   

我希望这样做:

 Parameters.Param[80] = {{"RevProtocol", 0x0001, DataType.Uint16, ReadWriteState.ReadOnly},  
                         {"HwProtocol", 0x0002, DataType.Uint16, ReadWriteState.ReadOnly}}

通过这种方式,我希望能够填充整个数组一次,但我似乎找不到正确的语法。这样的事情可能吗?

By doing like this i hope to be able to populate the entire array at once, but i cant seem to find the right syntax for this. Is something like this possible?

推荐答案

您很亲密。使用对象和集合初始化程序时,您仍然需要使用 new 关键字:

You are close. When using the object and collection initializers you still need to use the new keywords:

Parameters.Param = new Parameter[]
{
    new Parameter { ParamId = 0x0001, ParamName = "RevProtocol", Datatype = DataType.Byte },
    new Parameter { ParamId = 0x0002, ParamName = "HwProtocol", Datatype = DataType.TypeCell },
};

请在对象和集合初始化程序(C#编程指南)

这篇关于如何填充结构数组,而无需为每个成员使用一行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆