c# - C#:类中实例的存储;尝试获取其价值时获取 NullReferenceException
问题描述
我是 OOP 和 C# 的新手。这是我做的一个小实验:
Using System;
class A
{
public int X { get; set; }
public static A[] a = new A[10];
public static int i = 0;
public A()
{
this.X = -2;
}
public A(int x)
{
this.X = x;
}
public static void Add(A b)
{
if (i < 10) a[i] = b;
i++;
return;
}
public void Reveal()
{
Console.WriteLine(X);
}
public static void Show()
{
for (int j=0; j<=10; ++j)
{
a[j].Reveal();
}
}
}
我尝试创建一个类,它的实例存储在里面,最多 10 个对象。调用时A.Show()
会抛出 NullReferenceException:“对象引用未设置为对象的实例。” 正如我猜想的那样,它必须是对象a[j]
被创建,然后立即被销毁。所以它给出a[j]
一个空值,因此结果?*这是我的main
方法:
int val = 0;
while (val != -1)
{
Console.Write("create a new object. new value: ");
val = Console.ReadLine();
A a = new A(val);
A.Add(a);
};
A.Show();
Console.ReadKey();
return;
解决方案
请注意循环的上限条件:
for (int j=0; j<=10; ++j)
{
a[j].Reveal();
}
数组 a 分配了 10 个项目,但此代码显示您有 11 个项目从 0 到 10 开始,因此将其更改为略低于 10。并且还尝试比较所以正确的代码可以如下:
public static void Show()
{
for (int j = 0; j < 10; ++j)
{
a[j]?.Reveal();//Or if(a[j] != null)
}
}
并对读取客户端输入的行进行修改,必须如下:
val = int.Parse(Console.ReadLine());//If you are sure that the input
真正可转换为 int,或
int.TryParse(Console.ReadLine() , out int value);
if(value != 0)
{
val = value;
A a = new A(val);
A.Add(a);
}
else
{
throw new Exception();
}
推荐阅读
- sql - 在 SQL Server 中使用 STRING_AGG 获取唯一值
- sql - 获取查询结果的相反 Access 2016
- curl - SERP的卷曲编码
- java - 正则表达式准确地找到给定的字符串
- javascript - JS在for循环内创建动态变量
- kendo-ui - InvalidStateError - Kendo UI 上传
- express - TypeError:无法在“WebAssembly”上执行“编译”:响应 MIME 类型不正确。预期的“应用程序/wasm”
- python - 如何在 Python 中将两个 SVG 图像堆叠在一起?
- django - 将postgresql数据库中的数据检索到django中的字典中
- c# - 将声明映射到自定义 ApplicationUser 的属性