Search code examples
c#reflectionref

How to use reflection to get a method with a ref keyword?


Yeah so I set up a little TestClass to figure out what GetMethod would work to actually find the method Test(ref int i). But so far nothing worked.

[Button(nameof(Method))]
public bool whatever;

private void Test(ref int i)
{
    Debug.Log("Works");
}

private void Method()
{
    Type[] types = { typeof(int) };
    MethodInfo methodInfo = GetType().GetMethod(nameof(Test),
        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
        null, types, null);
    Debug.Log(methodInfo);
}

What am I supposed to do? I couldn't find anything on the web so far (for GetMethod specifically)


Solution

  • If you mix Eser + gcores you obtain:

    private void Test(ref int i)
    {
        Console.WriteLine(i);
        i++;
    }
    
    private void Test2(out int i)
    {
        i = 1000;
    }
    
    public void Method()
    {
        Type[] types = { typeof(int).MakeByRefType() };
    
        MethodInfo methodInfo = GetType().GetMethod(nameof(Test), BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);
    
        int num = 10;
        var pars = new object[] { num };
        methodInfo.Invoke(this, pars);
        Console.WriteLine(pars[0]);
    
        MethodInfo methodInfo2 = GetType().GetMethod(nameof(Test2), BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);
    
        var pars2 = new object[1];
        methodInfo2.Invoke(this, pars2);
        Console.WriteLine(pars2[0]);
    }
    

    Note the typeof(int).MakeByRefType(), and the fact that the object[] array containing the parameters is modified by the invoked method. I've added a second example with out that shows that you still use .MakeByRefType(), only you don't need to initialize the object[] array with a parameter. Ah and you should use the exact BindingFlags you need, not throw every BindingFlags contained in MSDN together. Static and non-static work differently :-)