Why can't I retrieve the value for parameters of type out or ref using Type.InvokeMember?

后端 未结 3 1185
梦如初夏
梦如初夏 2021-01-13 01:13

A long title, but I wanted it to be specific. The title is really the question. Even though the method that InvokeMember is calling has an out pa

3条回答
  •  庸人自扰
    2021-01-13 01:23

    Your second snippet is missing a rather essential line of code. It should look like this, assuming the out argument is of type string:

    object[] args = new object[1];      //necessary to retrieve ref/out parameter
    int result = Convert.ToInt32(typeof(Ability).InvokeMember(selectedMove, 
        BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, 
        null, null, args));
    string outValue = (string)args[0];  // <===  here!
    

    It should now also be obvious why your 1st snippet cannot work, you don't have a reference to the object[] array that you pass so you can never retrieve the modified argument.

提交回复
热议问题