Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...