3 回答

TA貢獻1818條經(jīng)驗 獲得超11個贊
private int myVar;
public int MyVar
{
get { return MyVar; }
}
布拉莫 您的應(yīng)用崩潰,沒有堆棧跟蹤。一直發(fā)生。
(注意使用大寫MyVar字母而不是小寫字母myVar)。

TA貢獻1784條經(jīng)驗 獲得超9個贊
Type.GetType
我看到很多人咬過的是Type.GetType(string)。他們想知道為什么它適用于他們自己的程序集中的類型,而某些類型像System.String,而不是System.Windows.Forms.Form。答案是,它只在當前程序集中和中出現(xiàn)mscorlib。
匿名方法
C#2.0引入了匿名方法,導(dǎo)致了如下討厭的情況:
using System;
using System.Threading;
class Test
{
static void Main()
{
for (int i=0; i < 10; i++)
{
ThreadStart ts = delegate { Console.WriteLine(i); };
new Thread(ts).Start();
}
}
}
那會打印出什么?好吧,這完全取決于調(diào)度。它會打印10個數(shù)字,但可能不會打印0、1、2、3、4、5、6、7、8、9,這可能是您期望的。問題在于i捕獲的變量是它,而不是在創(chuàng)建委托時的值。使用正確范圍的額外局部變量可以輕松解決此問題:
using System;
using System.Threading;
class Test
{
static void Main()
{
for (int i=0; i < 10; i++)
{
int copy = i;
ThreadStart ts = delegate { Console.WriteLine(copy); };
new Thread(ts).Start();
}
}
}
推遲執(zhí)行迭代器塊
這個“窮人的單元測試”沒有通過-為什么不呢?
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Test
{
static IEnumerable<char> CapitalLetters(string input)
{
if (input == null)
{
throw new ArgumentNullException(input);
}
foreach (char c in input)
{
yield return char.ToUpper(c);
}
}
static void Main()
{
// Test that null input is handled correctly
try
{
CapitalLetters(null);
Console.WriteLine("An exception should have been thrown!");
}
catch (ArgumentNullException)
{
// Expected
}
}
}
答案是,CapitalLetters直到MoveNext()首次調(diào)用迭代器的方法時,代碼源中的代碼才會執(zhí)行。
我的腦筋急轉(zhuǎn)彎頁面上還有其他怪異之處。

TA貢獻1828條經(jīng)驗 獲得超13個贊
重新拋出異常
重新拋出異常語義是獲得許多新開發(fā)人員的陷阱。
很多時間我看到如下代碼
catch(Exception e)
{
// Do stuff
throw e;
}
問題在于,它會擦除堆棧跟蹤,并使診斷問題變得更加困難,導(dǎo)致您無法跟蹤異常的起源。
正確的代碼是不帶參數(shù)的throw語句:
catch(Exception)
{
throw;
}
或?qū)惓0b在另一個異常中,然后使用內(nèi)部異常獲取原始堆棧跟蹤:
catch(Exception e)
{
// Do stuff
throw new MySpecialException(e);
}
- 3 回答
- 0 關(guān)注
- 800 瀏覽
添加回答
舉報