简体   繁体   中英

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." 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. You don't have a field called "test[0]" . It is called 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:

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. No it does not magically make them not null. It just disables a warning. One that could be useful to you, by the way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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