Reflection on a static overloaded method using an out parameter

后端 未结 1 1776
一个人的身影
一个人的身影 2020-12-30 05:06

I\'m having some issues with invoking an overloaded static method with an out parameter via reflection and would appreciate some pointers.

I\'m looking to dynamicall

相关标签:
1条回答
  • 2020-12-30 05:43

    You need to use the right BindingFlags and use Type.MakeByRefType for out and ref parameters. One second, and I'll have a code sample for you.

    For example,

    MethodInfo methodInfo = typeof(int).GetMethod(
        "TryParse",
        BindingFlags.Public | BindingFlags.Static,
        Type.DefaultBinder,
        new[] { typeof(string), typeof(int).MakeByRefType() },
        null
    );
    

    I should point out that invoking this is a little tricky too. Here's how you do it.

    string s = "123";
    var inputParameters = new object[] { "123", null };
    methodInfo.Invoke(null, inputParameters);
    Console.WriteLine((int)inputParameters[1]);
    

    The first null is because we are invoking a static method (there is no object "receiving" this invocation). The null in inputParameters will be "filled" for us by TryParse with the result of the parse (it's the out parameter).

    0 讨论(0)
提交回复
热议问题