How to populate array of structs, without using a

2019-07-30 19:36发布

问题:

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

I was hoping to do something like:

 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?

回答1:

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

See in more details in the Object and Collection Initializers (C# Programming Guide)



回答2:

As an alternative, and as in your comments you ask how to do it without having to specify each property name, you could use a class instead of an struct,an add a custom constructor:

class Parameter
{
    public string ParamName;
    public short ParamId;
    public DataType Datatype;
    public ReadWriteState ReadWrite;

    public Parameter(string name,short id,DataType dt,ReadWriteState rw)
    {
        this.ParamName = name;
        this.ParamId = id;
        this.Datatype = dt;
        this.ReadWrite = rw;
    }
}

This way, you could initialize your array like this:

Parameters.Param = new Parameter[] 
        { new Parameter("RevProtocol", 0x0001, DataType.Uint16, ReadWriteState.ReadOnly),
          new Parameter("HwProtocol", 0x0002, DataType.Uint16, ReadWriteState.ReadOnly)};


标签: c# arrays struct