samedi 10 avril 2021

Get method with an 'in' parameter through reflection

Imagine the following scenario, in which you would want to get the MethodInfo of the first method:

public class Foo
{
    public void Bar(in int value)
    {
    }

    public void Bar(string value)
    {
    }
}

If we would now look at the output of typeof(Foo).GetMethods(BindingFlags.Public | BindingFlags.Instance):

MethodInfo[6] { [Void Bar(Int32 ByRef)], [Void Bar(System.String)], [Boolean Equals(System.Object)], [Int32 GetHashCode()], [System.Type GetType()], [System.String ToString()] }

You can see that the first method, the one which we want to get the MethodInfo of, it says Int32 ByRef which is not the same as the Int32 type. I obvisously tried the following, but without any success:

typeof(Foo).GetMethod("Bar", BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(int) }, null)

I took at a closer look at the actual parameter with the following code:

typeof(Foo).GetMethods(BindingFlags.Public | BindingFlags.Instance)[0].GetParameters()[0]

Which outputs [Int32& value], which seems like a pointer of the the value type. So is there any way to get the Int32& type at runtime? Something along the lines of typeof(Int32&)?





Aucun commentaire:

Enregistrer un commentaire