C#多態的另一個簡單的例子

來源:互聯網
上載者:User

 

您好,多態的含義就是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 

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 

True 
False 
successful! 

請注意程式中有注釋的部分,這樣,我只需要一個方法就可以以安全的方法處理各種的資料。 

 

註:轉自百度知道

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.