【问题标题】:RuntimeBinderException with dynamic object calling public static method TryParseRuntimeBinderException 与动态对象调用公共静态方法 TryParse
【发布时间】:2019-08-01 21:34:09
【问题描述】:

我试图通过动态对象调用公共 TryParse 方法,但我收到 RuntimeBinderException...“System.Reflection.TypeInfo 不包含 TryParse 的定义”。运行时的动态对象具有 System.Boolean 类型,并且此类已定义该公共方法。

注意。这样做的原因是创建一个带有额外错误检查的通用 TryParse 方法,该方法将在应用程序中重复使用。

这是重现问题的代码:

    private (bool Success, T Value) TryParse<T>(string strval)
    {
        (bool Success, T Value) retval;
        dynamic dtype = typeof(T);
        retval.Success = dtype.TryParse(strval, out retval.Value);
        return retval;
    }

就我而言,我正在使用 TryParse("true") 测试该方法。 我究竟做错了什么? 谢谢。

【问题讨论】:

    标签: c#


    【解决方案1】:

    Bool.TryParse 是一个静态方法。 Booltypeof(Bool) 不是一回事。 typeof(Bool) 返回一个 System.Reflection.TypeInfo(继承自 System.Type)对象,该对象具有关于布尔类型的元数据,并且没有方法调用 TryParse

    可以使用反射从类型对象中获取TryParse 方法

    Type tType = typeof(T);
    object[] args = { "true", false };
    MethodInfo tryParseMethodInfo = tType.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public);
    bool result = (bool)tryParseMethodInfo.Invoke(null, args);
    

    但您最好使用System.Convert。你也可以看看使用here描述的方法

    【讨论】:

    • 我试图避免反思。思想(显然是错误的)动态可能是一种可能的方式。倾向于在您提供的链接上使用 Charlie Brown 的答案,以便拥有一个完成 TryParse + 应用程序特定错误检查的通用函数。
    猜你喜欢
    • 1970-01-01
    • 2011-04-19
    • 2013-07-22
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    相关资源
    最近更新 更多