【发布时间】:2016-09-20 13:24:52
【问题描述】:
以下代码的目的是使用 List.Find() 方法在通用列表中查找特定值。我在下面粘贴代码:
class Program
{
public static List<Currency> FindItClass = new List<Currency>();
public class Currency
{
public string Country { get; set; }
public string Code { get; set; }
}
public static void PopulateListWithClass(string country, string code)
{
Currency currency = new Currency();
currency.Country = country;
currency.Code = code;
FindItClass.Add(currency);
}
static void Main(string[] args)
{
PopulateListWithClass("America (United States of America), Dollars", "USD");
PopulateListWithClass("Germany, Euro", "EUR");
PopulateListWithClass("Switzerland, Francs", "CHF");
PopulateListWithClass("India, Rupees", "INR");
PopulateListWithClass("United Kingdom, Pounds", "GBP");
PopulateListWithClass("Canada, Dollars", "CAD");
PopulateListWithClass("Pakistan, Rupees", "PKR");
PopulateListWithClass("Turkey, New Lira", "TRY");
PopulateListWithClass("Russia, Rubles", "RUB");
PopulateListWithClass("United Arab Emirates, Dirhams", "AED");
Console.Write("Enter an UPPDERCASE 3 character currency code and then enter: ");
string searchFor = Console.ReadLine();
Currency result = FindItClass.Find(delegate(Currency cur) { return cur.Code == searchFor; });
Console.WriteLine();
if (result != null)
{
Console.WriteLine(searchFor + " represents " + result.Country);
}
else
{
Console.WriteLine("The currency code you entered was not found.");
}
Console.ReadLine();
}
}
我的问题是为什么 List 是 static ,那边用 static 的目的是什么。
public static List<Currency> FindItClass = new List<Currency>();
另一个问题是为什么在 find 方法中使用委托。
Currency result = FindItClass.Find(delegate(Currency cur) { return cur.Code == searchFor; });
【问题讨论】:
-
为什么
List是静态的?这应该是指向这个程序的作者的一个问题。关于delegate,这是因为Find需要Predicate<T>,其中T是您的列表类型,因此您可以为其提供anonymous method。 -
谷歌
static,我相信你会找到答案的。delegate关键字不再是必需的。你可以写:FindItClass.Find(cur => cur.Code == searchFor); -
您对
.Find使用代理的原因有何看法?您是否考虑过替代方案是什么? -
你想做什么?只需使用
List.Find? -
我正在尝试在通用列表中搜索特定值。我也很惊讶为什么在这里使用委托。这就是为什么我首先问了这样一个问题。