Assign a list of values to a struct in C#?
I have a struct (.NET 3.5):
struct ColumnHeadings
{
public string Name ;
public int Width ;
} ;
And when I try to assign a list of values to that struct I get a 'cannot implicitly convert type string/int to ...':
private void doSomething()
{
ColumnHeadings[,] ch = new ColumnHeadings[,]{{"column1",100},
{"column2",100},{"column3",100}};
}
Can the struct values be assigned in the same way as a multi-dimensional array? Or do I need to assign the values by using?:
ch.Name = "column 1";
UPDAT开发者_开发百科E:
Thanks to Marc's excellent feedback the correct solution is:
Struct:
struct ColumnHeadings
{
private readonly string name;
private readonly int width;
public string Name { get { return name; } }
public int Width { get { return width; } }
public ColumnHeadings(string name, int width)
{
this.name = name;
this.width = width;
}
}
Then in the method:
var ch = new[]{new ColumnHeadings("column1",100),
new ColumnHeadings("column2",100),
new ColumnHeadings("column3",100)};
And the link to why mutuable structs aren't a good idea.
firstly, that probably shouldn't be a struct
at all
The syntax will be:
ColumnHeadings[] ch = new ColumnHeadings[]{
new ColumnHeadings{Name="column1",Width=100},
new ColumnHeadings{Name="column2",Width=100}
};
However, in addition you have the issue of public fields, and the fact that this is a mutable struct - both of which are dangerous. No, really.
I would add a constructor:
var ch = new []{
new ColumnHeadings("column1", 100),
new ColumnHeadings("column2", 100)
};
with:
struct ColumnHeadings
{
private readonly string name;
private readonly int width;
public string Name { get { return name; } }
public int Width { get { return width; } }
public ColumnHeadings(string name, int width)
{
this.name = name;
this.width = width;
}
}
精彩评论