你做了什麼:
Search(list.Contains(item));
這將首先評估內表達list.Contains(item)
,這是一個布爾值,而不是用布爾返回值的函數。接下來,這個值而不是函數將傳遞到Search()
,這是不可能的,並導致編譯器錯誤。
你有兩個選擇:使用lambda表達式由Guffa已經指出:
class Program
{
static void Main(string[] args)
{
SearchTime();
}
static int Search(Func<bool> func)
{
int start = Environment.TickCount;
func();
int end = Environment.TickCount;
return end - start;
}
static void SearchTime()
{
IList<string> list = new []{"item"};
IDictionary<string, string> dictionary = new Dictionary<string, string> { { "key", "value" } };
int ticks1 = Search(() => list.Contains("item")); // Note: use() =>
int ticks2 = Search(() => dictionary.ContainsKey("key")); // Note: use() =>
/* some more code */
}
}
如果你不喜歡() =>
語法,你可以把代碼放到單獨的方法:
class Program2
{
static void Main(string[] args)
{
SearchTime();
}
static int Search(Func<bool> func)
{
int start = Environment.TickCount;
func();
int end = Environment.TickCount;
return end - start;
}
static void SearchTime()
{
int ticks1 = Search(ListContains); // Note: do not use() on ListContains
int ticks2 = Search(DictionaryContainsKey); // Note: do not use() on DictionaryContainsKey
/* some more code */
}
static IList<string> list = new[] { "" };
static bool ListContains()
{
return list.Contains("item");
}
static IDictionary<string, string> dictionary = new Dictionary<string, string> {{"key","value"}};
static bool DictionaryContainsKey()
{
return dictionary.ContainsKey("key");
}
}
請提供錯誤消息。 – Christian 2014-11-08 22:03:04
@ B.K。實際上我並沒有相同的論點,我使用現有的funcs,但是Guffa給出了確切的答案。也許它是相似的,但我在這個問題上找不到答案 – 2014-11-08 22:18:09