dimanche 18 juillet 2021

C# Reflection GetField().GetValue()

Given the following:

List<T> someList;

Where T is a type of some class:

public class Class1
{
  public int test1;
}

public class Class2
{
  public int test2;
}

How would you use Reflection to extract the values of test1/test2 stored in each List item? (The field names are provided)

My Attempt:

print(someList[someIndex]
.GetType()
.GetField("test1")
.GetValue(someList) // this is the part I'm puzzled about. What kind of variable should i pass here?

The Error I'm getting: "Object reference not set to an instance of an object", and according to microsoft docs the variable I should pass to GetValue is "The object whose field value will be returned." - which is what I'm doing.

Thanks for reading!





Aucun commentaire:

Enregistrer un commentaire