如何使用反射获取带有 ref 关键字的方法? [英] How to use reflection to get a method with a ref keyword?

查看:57
本文介绍了如何使用反射获取带有 ref 关键字的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,所以我设置了一个小 TestClass 来弄清楚 GetMethod 可以实际找到方法 Test(ref int i).但到目前为止没有任何效果.

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);
}

我该怎么办?到目前为止,我在网上找不到任何东西(特别是 GetMethod)

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

推荐答案

如果你混合使用 Eser + gcores 你得到:

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]);
}

注意 typeof(int).MakeByRefType(),以及包含参数的 object[] 数组被调用的方法修改的事实.我添加了第二个带有 out 的例子,它表明你仍然使用 .MakeByRefType(),只是你不需要初始化 object[] 带参数的数组.啊,您应该使用您需要的确切 BindingFlags,而不是将 MSDN 中包含的每个 BindingFlags 都扔在一起.静态和非静态的工作方式不同:-)

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 :-)

这篇关于如何使用反射获取带有 ref 关键字的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆