[英]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). 是的,所以我设置了一个TestClass来弄清楚哪种GetMethod可以实际找到方法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)
到目前为止,我在网上找不到任何东西(特别是对于GetMethod)
If you mix Eser + gcores you obtain: 如果将Eser + gcores混合使用,则会获得:
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. 请注意
typeof(int).MakeByRefType()
,以及包含参数的object[]
数组已由调用的方法修改的事实。 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. 我添加了第二个例子
out
,表示您仍然使用.MakeByRefType()
只有你没有需要初始化object[]
与参数数组。 Ah and you should use the exact BindingFlags
you need, not throw every BindingFlags
contained in MSDN together. 嗯,您应该使用所需的确切
BindingFlags
,而不是将MSDN中包含的每个BindingFlags
放在一起。 Static and non-static work differently :-) 静态和非静态工作不同:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.