Home>

Using reflection,
I want to store the created data in a List type, but it doesn't work.
Please give us your advice.

NullReferenceException: Object reference not set to an instance of an object
Corresponding source code

public class character
{
public int ID;
public string Name;
}

ListCharaList = new List();

private void Start ()
{
// Character creation
// -----
character test = new character ();

test.ID = 1;
test.Name = "Gueregere";

// store
// ---------
var add = this.GetType (). GetField ("CharaList"). GetType (). GetMethod ("Add");// ①
add.Invoke (CharaList, new character [] {test});

}

What I tried

I want to receive and store "CharaList" as a string.

① is written

this.GetType (). GetField ("CharaList"). GetType (). GetMethod ("Add");

Seems to be the problem.

In the first place, CharaList doesn't seem to be fetched by GetType (), so it becomes null.

this.GetType (). GetField ("CharaList"). GetType (). GetMethod ("Add");

  • Answer # 1

    As KOZ6.0 says, GetField cannot get the relevant field information because CharaList is not public.
    However, GetField does not give you the value of the CharaList field, but the information of the CharaList field (FiledInfoType).
    FieldInfoGet the value of the CharaList field from and then add to.

    var field = this.GetType ()
                    .GetField ("CharaList",
                               BindingFlags.NonPublic | BindingFlags.Instance);
    // After getting the value of CharaList field, cast it and then call add method
    var instance = (List<character>) field.GetValue (this);
    instance.Add (test);

    (Addition)

    By the way, I wish I could understand
    var instance = (List) field.GetValue (this);
    Of this part
    (List)
    Is it possible to process this part with a String string?

    I'm not sure,ListofTDoes that mean you can't cast because the part is variable?
    Then use more reflectionAddDo you call a method?

    var instance = field.GetValue (this);
    var add = instance.GetType (). GetMethod ("Add");
    add.Invoke (instance, new [] {test});

  • Answer # 2

    Unable to get an instance because CharaList is not public.
    Specify BindingFlags as the second argument of GetFields.

    var instance = this.GetType (). GetField ("CharaList",
                      BindingFlags.Instance | BindingFlags.NonPublic);