Home > Software design >  How to pass a ValueType arg to a Method in C# reflection?
How to pass a ValueType arg to a Method in C# reflection?

Time:05-01

My question is that a method requires a long type arg and i want to execute it by reflection. However, MethodInfo needs a array of object and long is a value type, it cannot be cast to object. How to solve it?

e.g.(just a example)

class A
{
  bool IsZero(long a)
  {
    return a == 0;
  }
}

CodePudding user response:

paramters must be specified via object[]

A myClassAInstance = new A();
MethofInfo mi = myClassAInstance.GetType().GetMethod("IsZero")
long myLong = 23;
var result = (bool)mi.Invoke(myClassAInstance, new object[]{myLong});

the myLong is automatically boxed.

if you have an int, you must cast it into long

long myInt = 11;
var result = (bool)mi.Invoke(myClassAInstance, new object[]{(long)myInt});
  • Related