简体   繁体   English

C# 反射类型.GetField 数组

[英]C# Reflection Type.GetField array

Im trying to read variable array from string and show it in console but each time I run the program Im getting error: "Object reference not set to an instance of an object."我试图从字符串中读取变量数组并在控制台中显示它,但每次运行程序时都会出现错误:“对象引用未设置为 object 的实例。” Can anyone suggest how to do this?谁能建议如何做到这一点?

my code:我的代码:

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));
}

This line:这一行:

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

Returns null.返回 null。 You don't have a field called "test[0]" .您没有名为"test[0]"的字段。 It is called test .它被称为test

So, let us get it:所以,让我们得到它:

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

And then read it:然后阅读它:

Positions pos = new Positions();

It is static, we don't need an instance:它是 static,我们不需要实例:

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

The exclamation mark is to tell the analyzer that these are not null.感叹号是告诉分析仪这些不是null。 No it does not magically make them not null.不,它不会神奇地使它们不是 null。 It just disables a warning.它只是禁用警告。 One that could be useful to you, by the way.顺便说一句,它可能对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM