一个奇怪的问题,关于重载!

 

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

 

复制代码
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");
 }
复制代码

 

 

posted on   xiao_p  阅读(2228)  评论(19编辑  收藏  举报

编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库

导航

< 2008年9月 >
31 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 1 2 3 4
5 6 7 8 9 10 11
点击右上角即可分享
微信分享提示