如何使用反射获取带有 ref 关键字的方法?
How to use reflection to get a method with a ref keyword?
是的,所以我设置了一个小的 TestClass 来弄清楚 GetMethod 将如何工作以实际找到方法 Test(ref int i)。但到目前为止没有任何效果。
[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)
您可以通过调用 GetMethod
的适当重载来找到具有指定参数类型的方法。要使参数成为引用类型,请使用代码:
Type[] types = { typeof(int).MakeByRefType() };
如果您混合使用 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]);
}
请注意 typeof(int).MakeByRefType()
,并且包含参数的 object[]
数组已被调用的方法修改。我添加了第二个带有 out
的示例,表明您仍然使用 .MakeByRefType()
,只是您不需要使用参数初始化 object[]
数组。啊,您应该使用您需要的确切 BindingFlags
,而不是将 MSDN 中包含的每个 BindingFlags
都放在一起。静态和非静态的工作方式不同:-)
是的,所以我设置了一个小的 TestClass 来弄清楚 GetMethod 将如何工作以实际找到方法 Test(ref int i)。但到目前为止没有任何效果。
[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)
您可以通过调用 GetMethod
的适当重载来找到具有指定参数类型的方法。要使参数成为引用类型,请使用代码:
Type[] types = { typeof(int).MakeByRefType() };
如果您混合使用 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]);
}
请注意 typeof(int).MakeByRefType()
,并且包含参数的 object[]
数组已被调用的方法修改。我添加了第二个带有 out
的示例,表明您仍然使用 .MakeByRefType()
,只是您不需要使用参数初始化 object[]
数组。啊,您应该使用您需要的确切 BindingFlags
,而不是将 MSDN 中包含的每个 BindingFlags
都放在一起。静态和非静态的工作方式不同:-)