使用out参数反映静态重载方法

时间:2011-01-19 20:45:06

标签: c# reflection static-methods

我在通过反射调用带有out参数的重载静态方法时遇到了一些问题,并且会对某些指针表示赞赏。

我希望动态创建类似System.Int32System.Decimal的类型,然后在其上调用静态TryParse(string, out x)方法。

以下代码有两个问题:

  • t.GetMethod("TryParse", new Type[] { typeof(string), t } )无法返回我期望的MethodInfo

  • mi.Invoke(null, new object[] { value.ToString(), concreteInstance })似乎已成功,但未将out参数concreteInstance设置为已解析的值

交织在此功能中,您可以看到一些临时代码,演示如果type参数设置为System.Decimal会发生什么。

public static object Cast(object value, string type)
{
    Type t = Type.GetType(type);
    if (t != null)
    {
        object concreteInstance = Activator.CreateInstance(t);
        decimal tempInstance = 0;

        List<MethodInfo> l = new List<MethodInfo>(t.GetMethods(BindingFlags.Static | BindingFlags.Public));

        MethodInfo mi;
        mi = t.GetMethod("TryParse", new Type[] { typeof(string), t } );  //this FAILS to get the method, returns null
        mi = l.FirstOrDefault(x => x.Name == "TryParse" && x.GetParameters().Length == 2);  //ugly hack required because the previous line failed
        if (mi != null)
        {
            try
            {
                bool retVal = decimal.TryParse(value.ToString(), out tempInstance);
                Console.WriteLine(retVal.ToString());       //retVal is true, tempInstance is correctly set
                object z = mi.Invoke(null, new object[] { value.ToString(), concreteInstance });
                Console.WriteLine(z.ToString());            //z is true, but concreteInstance is NOT set
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        return concreteInstance;
    }

    return value;
}

我需要做些什么来确保我的t.GetMethod()调用返回正确的MethodInfo?在concreteInstance来电中正确设置mi.Invoke()需要做些什么?

我知道关于这个主题有很多问题,但是大多数都涉及静态泛型方法或没有重载的静态方法。 This question类似但不重复。

1 个答案:

答案 0 :(得分:27)

您需要使用正确的BindingFlags并将Type.MakeByRefType用于outref参数。一秒钟,我将为您提供代码示例。

例如,

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

我应该指出,调用它也有点棘手。这是你如何做到的。

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

第一个null是因为我们正在调用静态方法(没有对象“接收”此调用)。 null中的inputParameters TryParse将由out填充给我们,并带有解析结果({{1}}参数)。