mardi 24 octobre 2017

C# Reflection Method.Invoke NullReferenceException [duplicate]

This question already has an answer here:

I've been trying to familiarize myself with reflection as much as I can and have been trying to invoke a method in an instanced class from a static class(and method). I'm not having much luck and keep getting a nullreferenceexception.

Type clss = Type.GetType(reader.GetString());
Debug.Log(clss.Name);
string methodname = reader.GetString();
object instance = clss.GetField("inst", BindingFlags.Static | BindingFlags.Public).GetValue(null);  Debug.Log(instance.GetType().IsInstanceOfType(instance));

int x = reader.GetInt();
float y = reader.GetFloat();

Debug.Log(x);
Debug.Log(y);

Debug.Log(instance.GetType().GetMethod(methodname, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) == null);

instance.GetType().GetMethod(methodname, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Invoke(instance, new object[] { x, y });

I've done multiple checks. The class type exists, the instance object isn't null, x and y aren't null. None of the variables I'm using are null but as soon as I use invoke it throws a nullreference.

Debug.Log(instance.GetType().IsInstanceOfType(instance));

tells me that it is indeed an instance of the class I want so I'm at a loss.

If anyone could help me that would be great, thanks!





Aucun commentaire:

Enregistrer un commentaire