Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

Setting a List to another List in C#

public static string[] traitNames = { "Happiness", "Respect", "Authority" };
private ArrayList arraysNames = new ArrayList() { traitNames, suppliesNames };
string[] currentArrayNames = new string[] { arraysNames[i1] };//error message here

Error message: Cannot implicitly convert 'object' to 'string'. What can I do to make currentArrayNames = traitNames via. referencing it through arraysNames? Thanks! Note: I did not include suppliesNames, although it does exist, much similar to traitNames.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that you're using the non-generic ArrayList type - so the compile-time type of arraysNames[i1] is object, not string[]. You should almost never use ArrayList in modern code - since 2005, the preferred generic equivalent has been List<T>. So this code will compile:

public static string[] traitNames = { "Happiness", "Respect", "Authority" };
private List<string[]> arraysNames = new List<string[]> { traitNames, suppliesNames };

// Later in code
string[] currentArrayNames = arraysNames[i1];

Note that this doesn't create a new array - it just uses the existing one. I'm assuming that's what you wanted, really.

If you absolutely can't change the type of arraysNames, you can just cast instead:

string[] currentArrayNames = (string[]) arraysNames[i1];

It's definitely better to use List<string[]> instead though.

As a side-note, I'd strongly recommend avoiding making fields public as you have with traitNames.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...