【发布时间】:2021-07-07 23:39:06
【问题描述】:
我试图从字符串中读取变量数组并将其显示在控制台中,但每次运行程序时都会出现错误:“对象引用未设置为对象的实例。”谁能建议如何做到这一点?
我的代码:
public class Positions
{
public static string[] test = { "test", "test2" };
}
private void test()
{
Positions pos = new Positions();
Type type = typeof(Positions);
FieldInfo fi = type.GetField("test[0]");
Console.WriteLine(fi.GetValue(pos));
}
【问题讨论】:
-
该字段是
test,而不是test[0]- 您需要在之后应用索引。另外,对于静态字段,您需要将null作为目标对象传递 -
@MarcGravell 好的,我将最后一行更改为“Console.WriteLine(myFieldInfo.GetValue(null));”但是我应该在哪里应用索引?
标签: c# reflection computer-science