c# System.NullReferenceException 同时将值赋给枚举数组
c# System.NullReferenceException while assign the value to Enum array
我想将值添加到 null 枚举数组。但是我在 运行 时间内遇到了 null 异常。我该如何解决这个问题?
我的枚举是
public enum Name
{
Arun, Kumar, Mohan, Jerwin
}
然后我创建枚举数组。
private static Name[] names; //here I can`t set the size. Because user can pass the input as per their need.
现在我从用户那里获取值并添加到枚举数组集合中。但是我在代码中遇到空异常。
public static string GetName(Name input)
{
names[0] = input;
//My implementation
}
我在行 names[0] = input;
中收到错误。
我的例外是
An unhandled exception of type 'System.NullReferenceException' occurred in my.dll
Additional information: Object reference not set to an instance of an object.
如何将此用户输入添加到枚举数组?
不需要数组,因为数组大小应该是固定的。你需要一个List<Name>
。列表有 "dynamic" 大小并且可以添加元素。
private static List<Name> names = new List<Name>();
然后:
public static string GetName(Name input)
{
names.Add(input)
(从技术上讲,您可以使用数组来执行此操作,因为可以调整数组的大小,但这样做通常是错误的...正确的工具适合正确的工作)
请注意,您所做的有点腥...闻起来很臭。将枚举(一种在编译时确定的构造,通常用于小型固定集)用于名称之类的东西很奇怪。通常有不可数的名字(除了一些小的例外......美国各州的名字只有 50 个,而且它们很少改变......只有 7 个罗马国王,这不会改变并且等等)
我想将值添加到 null 枚举数组。但是我在 运行 时间内遇到了 null 异常。我该如何解决这个问题?
我的枚举是
public enum Name
{
Arun, Kumar, Mohan, Jerwin
}
然后我创建枚举数组。
private static Name[] names; //here I can`t set the size. Because user can pass the input as per their need.
现在我从用户那里获取值并添加到枚举数组集合中。但是我在代码中遇到空异常。
public static string GetName(Name input)
{
names[0] = input;
//My implementation
}
我在行 names[0] = input;
中收到错误。
我的例外是
An unhandled exception of type 'System.NullReferenceException' occurred in my.dll
Additional information: Object reference not set to an instance of an object.
如何将此用户输入添加到枚举数组?
不需要数组,因为数组大小应该是固定的。你需要一个List<Name>
。列表有 "dynamic" 大小并且可以添加元素。
private static List<Name> names = new List<Name>();
然后:
public static string GetName(Name input)
{
names.Add(input)
(从技术上讲,您可以使用数组来执行此操作,因为可以调整数组的大小,但这样做通常是错误的...正确的工具适合正确的工作)
请注意,您所做的有点腥...闻起来很臭。将枚举(一种在编译时确定的构造,通常用于小型固定集)用于名称之类的东西很奇怪。通常有不可数的名字(除了一些小的例外......美国各州的名字只有 50 个,而且它们很少改变......只有 7 个罗马国王,这不会改变并且等等)