【问题标题】:C# Reflection Type.GetField arrayC# 反射 Type.GetField 数组
【发布时间】: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


【解决方案1】:

这一行:

FieldInfo fi = type.GetField("test[0]");

返回空值。您没有名为"test[0]" 的字段。它被称为test

那么,让我们来看看吧:

var fi = typeof(Positions).GetField(nameof(Positions.test));

然后阅读:

Positions pos = new Positions();

它是静态的,我们不需要实例:

var fi = typeof(Positions).GetField(nameof(Positions.test))!; // We know it is not null
var value = fi.GetValue(null) as string[];
Console.WriteLine(value[0]); // value could be null

感叹号是告诉分析器这些不为空。不,它不会神奇地使它们不为空。它只是禁用警告。顺便说一句,这可能对你有用。

【讨论】:

  • 非常感谢!我已经尝试了几个小时......
  • @mareklipka12 有很多类似的帖子 - bing.com/… 你真的不需要等这么久才能找到答案。
猜你喜欢
  • 2022-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多