Array Question - Regarding Index. c #
Firstly Hello, This is my first post on this forum.
I am completing a project in my second year of an IT degree. It's a baptism of fire as it's a tcp/ip utility in C# and my only other experience of programming in a foundation module in Java in the first year.
My problem is that part of my programm logs NIC card error codes using NetworkAdapter class Availability property. I have made an array of the error code descriptions as they are not automatically returned with the code. Obviously arrays being 0 based and the codes start at 1 I have had to put a null value as the entry in the array. Is there a more robust solution or is that the only way? I ask because i understand that null values in arrays are frowned upon.
string[] availabilityArray = new string[] {"", "Other", "Unknown", "Run开发者_开发技巧ning or Full Power", "Warning", "In Test", "Not Applicable", "Power Off", "Off Line", "Off Duty", "Degraded", "Not Installed", "Install Error", "Power Save - Unknown" + "\n" +"The device is known to be in a power save state, but its exact status is unknown.", "Power Save - Low Power Mode" + "/n" +"The device is in a power save state, but still functioning, and may exhibit degraded performance.", "Power Save - Standby" + "/n" +"The device is not functioning, but could be brought to full power quickly.", "Power Cycle", "Power Save - Warning" + "/n" + "The device is in a warning state, though also in a power save state.",};
Many Thanks
Your solution is OK.
You could also use a Dictionary<int, string>
.
There are multiple ways to handle this:
- Keep your first element
Subtract 1 from each error code before looking it up:
string text = availabilityArray[errorCode - 1];
Use a dictionary:
Dictionary<int, string> availability = new Dictionary<int, string> { { 1, "Other" }, { 2, "Unknown" }, };
This would also handle gaps, you could easily skip to code 10 in the above list and continue, but you would need explicit code to detect whether an error code is present in the dictionary:
string text; if (availability.TryGetValue(errorCode, out text)) // is there else // is not
instead of using an array you could use a:
Dictionary<int, string>
so you can map your error codes and messages in a way which is independent from the collection's index.
In the name of obscurity you should be able to make a 1 indexed array in C#:
Array.CreateInstance(typeof(string), new[] { 100 /* array length */ }, new { 1 } /* offset */);
Use Enum
enum Availability
{
Other = 1,
Unknown,
Running_or_Full_Power,
Warning, In_Test,
Not_Applicable,
Power_Off,
Off_Line,
Off_Duty, Degraded
};
精彩评论