现在的位置: 首页 > 综合 > 正文

C#多态的另一个简单的例子

2013年06月07日 ⁄ 综合 ⁄ 共 1530字 ⁄ 字号 评论关闭

 

您好,多态的含义就是C#中允许多个方法的方法名相同,只要它们的方法签名不同就可以。 

这里有两个概念,方法名是方法的一部分,例如一个方法: 
public static void hello(int a, int b) 
在这个方法中,hello被称为方法名。 

方法签名指的是方法名和方法参数列表的构造,同样对于上面的方法,它的方法签名是: 
hello(
int a, int b) 

多态性的作用是极大的,您可能已经知道,下面的代码是可以通过编译的: 
using System; 

namespace Test 

 
public class MainClass 
 

  
public static void Main() 
  

  Console.WriteLine(
"hahaha"); 
  Console.WriteLine(
5); 
  Console.WriteLine(
true); 
  }
 
 }
 
}
 

这段代码的输出是:
hahaha 
5 
true 

C#是一种强类型语言,它的不同类型必须经过转换才能进行处理,那么为什么一个WriteLine()方法既可以输出字符串类型的常量,又可以输出整型和布尔型的常量呢?原因就在于

多态性。 

下面是一个例子,我写了一个类Test,它包含一系列方法,方法名都是Print,我对不同的输入参数进行了处理,没有使用WriteLine方法的重载。 

//test.cs 
//可以使用 csc test.cs 编译这段代码或复制到VC#中。 
using System; 

namespace TestFunc 

 
public class Test 
 

  
public static void Print(string str) 
  

   Console.WriteLine(str); 
  }
 

  
public static void Print(int i) 
  

   Console.WriteLine(i.ToString());
//调用ToString方法把整型转换为string类型。 
  }
 

  
public static void Print(bool b) 
  

   
if (b == true)//判断后输出结果。 
   
    Console.WriteLine(
"True"); 
   }
 
   
else 
   

    Console.WriteLine(
"False"); 
   }
 
  }
 

  
public static void Print(params string[] str) 
  

   
//这个方法实现了对未知数量的参数的输出。使用params关键字。 
   for (int i = 0; i < str.Length; ++i) 
   

    Console.WriteLine(str[i]); 
   }
 
  }
 
 }
 

    
public class MainClass 
 

  
public static void Main() 
  

   
bool a = false
   Test.Print(
"david","jack","mike"); 
   Test.Print(
5); 
   Test.Print(
true); 
   Test.Print(a); 
   Test.Print(
"successful!"); 
  }
 
 }
 
}
 

程序执行的输出是: 
david 
jack 
mike 
5 
True 
False 
successful
! 

请注意程序中有注释的部分,这样,我只需要一个方法就可以以安全的方法处理各种的数据。 

 

注:转自百度知道

抱歉!评论已关闭.