c# - 这是一个错误吗? MissingMethodException 以 0 作为参数访问私有(private)静态方法

标签 c# visual-studio-2010 .net-4.0

我不确定我是否应该在这里问这个问题,但我们开始吧,在对一个参数为 short 的私有(private)静态方法进行单元测试时,只有当此参数为 0 时,我才会收到 MissingMethodException。

我正在使用针对 Framework 4(完整)的 VS 2010 SP1,这是重现此错误的最低限度代码(我们正在升级 VB6 代码,所以请不要无礼):

    [DataContract]
  public enum NotificationResult
  {
    [EnumMember]
    Success,
    [EnumMember]
    StoredError,
    [EnumMember]
    InvalidId,
    [EnumMember]
    OperationError,
  }

    public sealed class NotificationContext
  {
    private static NotificationResult GetExecuteResult(short result)
    {
      NotificationResult executeResult;
      switch (result)
      {
        case 0:
          executeResult = NotificationResult.Success;
          break;
        case 1:
          executeResult = NotificationResult.StoredError;
          break;
        case 2:
          executeResult = NotificationResult.InvalidId;
          break;
        default:
          executeResult = NotificationResult.OperationError;
          break;
      }

      return executeResult;
    }
  }

这是我测试代码的方式:

 PrivateType privateHelperType = new PrivateType(typeof(NotificationContext));
      var actual = (NotificationResult)privateHelperType.InvokeStatic(
        "GetExecuteResult", (short)1);
      var actual2 = (NotificationResult)privateHelperType.InvokeStatic(
        "GetExecuteResult", (short)0); //here is where i get the exception

在第一次调用中,我得到了预期的结果,在第二次调用中,我得到了异常(我添加了强制转换,以为异常可能是因为它没有找到以 int 作为参数的方法)。

有人能重现这种行为吗?我做错了什么吗?

感谢您的帮助。

最佳答案

问题是这个方法有两个重载(还有其他的,但在这里不重要):

不同之处在于第二个重载有一个BindingFlags类型的参数,它是一个enum。当您将文字 0 作为第二个参数传递时,会选择此重载,因为文字 0 可隐式转换为任何 enum 并且不使用params 被认为比在重载决议中使用它更好。所以,基本上

  • privateType.InvokeStatic("GetExecuteResult", 1)编译成privateType.InvokeStatic("GetExecuteResult", new object[] { 1 })
  • privateType.InvokeStatic("GetExecuteResult", 0)编译成privateType.InvokeStatic("GetExecuteResult", 0, new object[] { })

这就是您遇到问题的原因。我认为避免它的最简洁方法是显式创建数组:

privateType.InvokeStatic("GetExecuteResult", new object[] { 0 })

除非在您的代码中您没有将文字 0 传递给该方法,否则您首先对其进行转换。根据规范,在这种情况下不应选择 BindingFlags 重载。但是errors like this are a known bug ,这不会被修复,因为它会破坏一些工作程序。

关于c# - 这是一个错误吗? MissingMethodException 以 0 作为参数访问私有(private)静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8904806/

相关文章:

c# - 如何在另一个线程完成时停止一个线程

c - 从 64 位整数类型加载 __m64?

visual-studio-2010 - 在Visual Studio中滚动导致文本变得不可读

C# GUI 线程错误

c# - 直接反/序列化到/从 XML Linq

c# - C#中如何从数据表中逐行读取数据

c# - Visual-C++ DLL 将 2-3 兆字节复制到 C# 缓冲区的最快方法是什么?

c# - LINQ to NHibernate,如何做这个查询

windows - 在线程中调用 SHGetFileInfo 以避免 UI 卡住

c# - 在编辑器 session 之间存储编辑器值