我在使用WinForms一段時間後開始編寫ASP.NET Web應用程序。經過幾次嘗試錯誤的錯誤,我終於意識到這兩者有什麼不同。儘管我知道很多關於C#的高級內容,但我從未學會在推進一些更困難的事情之前應該知道的小事,所以我在這裏問這些問題,可能會遇到一些問題不會回答低谷的教程,而是開發者的體驗,所以我會開始:靜態方法,GDI +,異常處理瑣碎問題
在GDI +使用圖形時,這是正確的方法嗎?
Bitmap bitmap;
Graphics g;
protected void Page_Load(object sender, EventArgs e)
{
Bitmap bitmap = new Bitmap(200,200);
Graphics g = Graphics.FromImage(bitmap);
}
public void SomeMethod()
{
g.DrawRectangle(somePen,someRectangle);
}
public void SomeOtherMethod()
{
g.DrawRectangle(someOtherPen,someOtherRectangle);
}
例子:
Bitmap bitmap;
Graphics g;
protected void Page_Load(object sender, EventArgs e)
{
Bitmap bitmap = new Bitmap(200,200);
Graphics g = Graphics.FromImage(bitmap);
}
public void SomeMethod()
{
g.DrawRectangle(somePen,someRectangle);
}
public void SomeOtherMethod()
{
g = Graphics.FromImage(bitmap);
g.DrawRectangle(someOtherPen,someOtherRectangle);
}
例子:
Bitmap bitmap;
protected void Page_Load(object sender, EventArgs e)
{
Bitmap bitmap = new Bitmap(200,200);
}
public void SomeMethod()
{
Graphics g = Graphics.FromImage(bitmap);
g.DrawRectangle(somePen,someRectangle);
//Dispose pens,graphics..
}
public void SomeOtherMethod()
{
Graphics g1 = Graphics.FromImage(bitmap);
g1.DrawRectangle(someOtherPen,someOtherRectangle);
//Dispose pens,graphics..
}
關於靜態方法:
我有一堆的方法不適合任何實例類,像一些SQL方法,我需要在應用程序的不同部分:
- 我應該創建新的實例類,把它們放在裏面。而當我需要其中一個創建新實例和調用方法時,我需要。
- 我應該創建一個新的靜態類,只需要調用我需要的那個 而不創建實例。
我學會了靜態變量是全局的難題,這意味着如果一個用戶改變它,另一個用戶將在該變量中具有該值。
Static Int ID = 0;
UserA triggers some Sql method to fetch his ID into variable ID.
UserB comes to site and the ID value is UserA ID
在靜態方法中定義localy的變量是否共享此行爲? 使用靜態方法有沒有像這樣的危險?
關於空: 難道真的nessecery檢查對象爲空,如果你確保你對可空類型變量的使用方法不返回null:
List<string> list = new List<string>();
//List can only become null if we call some method that returns null or if we do
list = null;
關於異常處理: 我在幾個偶爾發生的事情上讀到類似「不要捕捉你無法處理的異常」的東西,這是什麼意思?
爲什麼把try/catch語句「只是爲了確保該應用程序不chrash」裏面的方法不對其他然後表現?
嗨!你能把你的問題分成3個不同的問題嗎? – 2012-02-16 11:21:21
@rodrigovedovato我沒有時間去檢查答案,現在猜測沒有意義再分裂,對不起。 – formatc 2012-02-17 12:41:40