zoukankan      html  css  js  c++  java
  • 一个奇怪的问题,关于重载!

    今天在 写一个 重载的 时候发现了 一个很奇怪的问题, 先看这样的一段程序!

    static void Main(string[] args)
    {
         test(null);
    }

    static void test(object obj)
    {
         Console.WriteLine("obj");
    }

    static void test(object[] obj)
    {
         Console.WriteLine("obj array");
    }

    程序 输出是 “obj array”。


    可是,为什么test(null); 会自动调用 

     static void test(object[] obj)
     {
          Console.WriteLine("obj array");
     }

    这个方法呢?

    试着用 il 打开,也没有发现有什么区别,il 代码如下

    .method private hidebysig static void  Main(string[] args) cil managed
    {
      .entrypoint
      // Code size       9 (0x9)
      .maxstack  8
      IL_0000:  nop
      IL_0001:  ldnull
      IL_0002:  call       void ConsoleApplication1.Program::test(object[])
      IL_0007:  nop
      IL_0008:  ret

    } // end of method Program::Main 

    ************这个是main方法的************

    .method private hidebysig static void  test(object[] obj) cil managed
    {
      // Code size       13 (0xd)
      .maxstack  8
      IL_0000:  nop
      IL_0001:  ldstr      "obj array"
      IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
      IL_000b:  nop
      IL_000c:  ret
    } // end of method Program::test

     ************这个是test(object[] obj)方法的************

    .method private hidebysig static void  test(object obj) cil managed
    {
      // Code size       13 (0xd)
      .maxstack  8
      IL_0000:  nop
      IL_0001:  ldstr      "obj"
      IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
      IL_000b:  nop
      IL_000c:  ret
    } // end of method Program::test

      ************这个是test(object obj)方法的************


    总结:最好的解决办法就是增加一个没有参数的重载,这样,一切就都ok了!(感谢 曲滨*銘龘鶽

     static void Main(string[] args)
     {
          test();
     }

     
    static void test()
     {
         Console.WriteLine(
    "null");
     }

     
    static void test(object obj)
     {
         Console.WriteLine(
    "obj");
     }

     
    static void test(object[] obj)
     {
          Console.WriteLine(
    "obj array");
     }
  • 相关阅读:
    典型分布式系统分析:MapReduce
    linux下如何查看自己都装了什么服务
    docker
    linux的命令操作
    IDEA去除掉虚线,波浪线,和下划线实线的方法
    在linux下安装配置rabbitMQ详细教程
    在linux下安装配置rabbitMQ详细教程
    Shell特殊变量:Shell $0, $#, $*, $@, $?, $$和命令行参数
    shell之startup
    shell脚本特殊变量($0、$1、$2、 $?、 $# 、$@、 $*)
  • 原文地址:https://www.cnblogs.com/xiao_p/p/1285041.html
Copyright © 2011-2022 走看看