Top Ten Traps in C# for C++ Programmers中文版(轉)(2)
2024-07-21 02:22:20
供稿:網友
陷阱六.虛方法必須被顯式重載
在c#中,如果程序員決定重載一個虛方法,他(她)必須顯式使用override關鍵字。
讓我們考察一下這樣做的好處。假定公司a寫了一個window類,公司b購買了公司a的window類的一個拷貝作為基類。公司b的程序員從中派生【譯注:原文為...using...,從下文來看,顯然是“派生”之意。事實上,使用類的方式還有“組合”(也有說為“嵌入”或“包容”(com語義)等等),后者不存在下文所描述的問題】出listbox類和radiobutton類。公司b的程序員不知道或不能控制window類的設計,包括公司a將來對window類可能做的修改。
現在假定公司b的程序員決定為listbox類加入一個sort方法:
public class listbox : window
{
public virtual void sort() {}
}
這是沒有問題的—直到公司a的window類作者發布了window類的版本2,公司a的程序員向window類也加入了一個public的sort方法:
public class window
{
public virtual void sort() {}
}
在c++中,window類新的虛方法sort將會作為listbox虛方法的基類方法。當你試圖調用window的sort時,實際上調用的是listbox的sort。c#中虛方法【譯注:原文寫成virtual function】永遠被認為是虛擬調度的根。這就是說,只要c#找到了一個虛方法,它就不會再沿著繼承層次進一步尋找了,如果一個新的sort虛方法被引入window,listbox的運行時行為不會被改變。當listbox再次被編譯時,編譯器會發出如下警告:
"/class1.cs(54,24): warning cs0114: 'listbox.sort()' hides inherited member 'window.sort()'.
如果要使當前成員重載實現,可加入override關鍵字。否則,加上new關鍵字。
如果想要移去這個警告,程序員必須明確指明他的意圖。可以將listbox的sort方法標為new,以指明它不是對window的虛方法的重載:
public class listbox : window
{
public new virtual void sort() {}
}
這樣編譯器就不會再警告。另一方面,如果程序員想重載window的方法,只要顯式加上override關鍵字即可。
陷阱七:不可以在頭部進行初始化
c#里的初始化不同于c++。假定你有一個類person,它有一個私有成員變量age;一個派生類employee,它有一個私有成員變量salaryleverl。在c++中,你可以在employee構造器的成員初始化列表部分初始化salarylevel:
employee::employee(int theage, int thesalarylevel):
person(theage) // 初始化基類
salarylevel(thesalarylevel) // 初始化成員變量
{
// 構造器體
}
在c#中,這個構造器是非法的。盡管你仍可以如此初始化基類,但對成員變量的初始化將導致一個編譯時錯誤。你可以在成員變量聲明處對其賦初始值:
class employee : public person
{
// 在這兒聲明
private salarylevel = 3; //初始化
}
【譯注:以上代碼有誤lc#中,正確寫法如下:
class employee: person
{
private int salarylevel = 3;
}
】
你不需要在每一個類聲明的后面都加上一個分號。每一個成員都必須要有顯式的訪問級別聲明。
陷阱8.不能把布爾值轉換為整型值
在c#中,布爾值(true、false)不同于整型值。因此,不能這么寫:
if ( somefuncwhichreturnsavalue() )//【譯注:假定這個方法不返回布爾值】
也不能指望如果somefuncwhichreturnsavalue返回一個0它將等于false,否則為true。一個好消息是誤用賦值操作符而不是相等操作符的老毛病不會再犯了。因此,如果這么寫:
if ( x = 5 )
將會得到一個編譯時錯誤,因為x = 5的結果為5,而它不是布爾值。
【譯注:以下是c++里一不小心會犯的邏輯錯誤,編譯器不會有任何提示l運行得很順暢,不過結果并不是你想要的:
c++:
#include "stdafx.h"
int main(int argc, char* argv[])
{
int n = 0;
if (n = 1)//編譯器啥都沒說l一般推薦寫為1 == n,萬一寫成1 = n編譯器都不同意j
{
printf("1/n");
}
else
{
printf("0/n");
}
return 0;
}
以上運行結果為1,這未必是你想要的。
c#:
using system;
public class rytestboolapp
{
public static void main()
{
int n = 0;
if (n = 1)//編譯器不同意j無法將int轉換成bool
{
console.writeline("1");
}
else
{
console.writeline("0");
}
}
}
但如果是這種情況:
bool b = false;
if (b = true)
...
不管是c++還是c#都沒招l
】
【譯注:c++程序員一般是喜歡這種自由的寫法:
if (myref)
if (myint)
但在c#里,必須寫成:
if (myref != null)//或if (null != myref)
if (myint != 0)//或if (0 != myint)
等。
】
陷阱九.switch語句不可“貫穿”【譯注:即fall through,beta2的聯機文檔就是如此譯法】
在c#中,如果在case語句里有代碼的話,那它就不可“貫穿”到下一句。因此,盡管下面代碼在c++里合法,但在c#中則不然:
switch (i)
{
case 4:
callfuncone();
case 5: // 錯誤,不可以“貫穿”
callsomefunc();
}
為了達到這個目的,需要顯式地使用goto語句:
switch (i)
{
case 4:
callfuncone();
goto case 5;
case 5:
callsomefunc();
}
如果case語句沒做任何事(里面沒有代碼)就可以“貫穿”:
switch (i)
{
case 4: // 可以“貫穿”
case 5: // 可以“貫穿”
case 6:
callsomefunc();
}
【譯注:以下是使用switch的完整例子,它還說明了switch語句的參數類型可以是字符串,此例同時還演示了屬性的使用方法。
using system;
class ryswitchtest
{
public ryswitchtest(string astr)
{
this.strproperty = astr;
}
protected string strfield;
public string strproperty
{
get
{
return this.strfield;
}
set
{
this.strfield = value;
}
}
public void switchstrproperty()
{
switch (this.strproperty)
{
case ("ry01"):
console.writeline("ry01");
break;
case ("ry02"):
console.writeline("ry02");
break;//如果這一行注釋掉,編譯器會報控制不能從一個case標簽(case "ry02":)貫穿到另一個標簽,如果你確實需要,可以這么寫:goto case ("ry03");或goto default。
case ("ry03"):
console.writeline("ry03");
break;
default:
console.writeline("default");
break;
}
}
}
class ryswitchtestapp
{
public static void main()
{
ryswitchtest rst = new ryswitchtest("ry02");
rst.switchstrproperty();
}
}
】
陷阱十.c#需要明確的賦值操作
c#要求必須明確地進行賦值操作,這就意味所有變量在使用前必須被賦值。因此,盡管你可以聲明未初始化的變量,但在它擁有值之前是不可以被傳遞到方法的。
這就引出了一個問題—當你僅僅是想將變量用作一個“出”參數按引用傳遞給方法時。例如,假定有個方法,返回當前的小時、分鐘和秒。如果這么寫:
int thehour;
int theminute;
int thesecond;
timeobject.gettime( ref thehour, ref theminute, ref thesecond)
編譯將出錯,因為在使用thehour、theminute和thesecond前,它們沒有被初始化:
use of unassigned local variable 'thehour'
use of unassigned local variable 'theminute'
use of unassigned local variable 'thesecond'
可以將它們初始化為0或者其它什么無傷大雅的值以讓討厭的編譯器安靜下來:
int thehour = 0;
int theminute = 0;
int thesecond = 0;
timeobject.gettime( ref thehour, ref theminute, ref thesecond)
但是這種寫法實在太愚蠢!我們的本意不過是想把這些變量按引用傳遞到gettime,在其中改變它們的值。為了解決這個問題,c#提供了out參數修飾符。這個修飾符避免了對引用參數也要初始化的需求。例如,為gettime提供的參數沒有提供給方法任何信息,它們僅僅是想從方法里取得信息。因此,把這三個參數都標記為out型的,就避免了在方法外初始化它們的需要。但當從被傳入的方法返回時,out參數必須被賦值。下面是改變后的gettime參數聲明:
public void gettime(out int h, out int m, out int s)
{
h = hour;
m = minute;
s = second;
}
下面則是對gettime方法的新的調用方式:
timeobject.gettime( out thehour, out theminute, out thesecond);
【譯注:完整示例如下:
c#:[例1:使用ref修飾的方法參數]
using system;
class ryreftest
{
public ryreftest()
{
this.intfield = 1;
this.strfield = "strfield";
}
protected int intfield;
protected string strfield;
public void getfields(ref int aint, ref string astr)
{
aint = this.intfield;
astr = this.strfield;
}
}
class ryreftestapp
{
public static void main()
{
ryreftest rrt = new ryreftest();
int intvar = 0;//如果是int intvar; 編譯器會報使用了未賦值的變量intvar
string strvar = "0";//如果是string strvar; 編譯器會報使用了未賦值的變量strvar
rrt.getfields(ref intvar, ref strvar);
console.writeline("intvar = {0}, strvar = {1}", intvar, strvar);
}
}
c#:[例2:使用out修飾的方法參數]
using system;
class ryreftest
{
public ryreftest()
{
this.intfield = 1;
this.strfield = "strfield";
}
protected int intfield;
protected string strfield;
public void getfields(out int aint, out string astr)
{
aint = this.intfield;
astr = this.strfield;
}
}
class ryreftestapp
{
public static void main()
{
ryreftest rrt = new ryreftest();
int intvar;//這樣就可以了,如果寫成int intvar = 0;當然也沒問題j
string strvar; //這樣就可以了,如果寫成string strvar = "0";當然也沒問題j
rrt.getfields(out intvar, out strvar);
console.writeline("intvar = {0}, strvar = {1}", intvar, strvar);
}
}
】