2016-09-20 8 views
-4

以下のコードの目的は、List.Find()メソッドを使用して汎用リスト内の特定の値を見つけることです。私は以下のコードを貼り付けています:リストはあそこ静的使用する目的が何であるか、静的である理由Genericリスト内の特定の値を検索

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(); 
    } 
} 

私のクエリがあります。

public static List<Currency> FindItClass = new List<Currency>(); 

もう1つのクエリは、その上でfindメソッド内でデリゲートが使用される理由です。

Currency result = FindItClass.Find(delegate(Currency cur) { return cur.Code == searchFor; }); 
+3

を* 'List'は静的でなぜ*このプログラムの作家を指摘し、質問する必要があることを?。 'delegate'に関しては、' Find'が 'Predicate 'を期待しているからです。 'T'はあなたのリストの型ですので、[* anonymous method *](https://msdn.microsoft。 com/ja-us/library/0yw3tz5k.aspx)をそれに追加します。 –

+0

Google静的な答えを見つけられると確信しています。 'delegate'キーワードはもはや必要ではありません。 'FindItClass.Find(cur => cur.Code == searchFor);' –

+0

'.Find'にデリゲートが使用された理由は何ですか?あなたはその代替案が何であるか考えましたか? –

答えて

1

小さなコンソールアプリであるため、リストは静的です。 Mainは静的なので、 "Program"クラスの静的変数にアクセスできるのは、 "Program"という新しいインスタンスを作成することなくです。

staticキーワードは、その変数のインスタンスがプログラム全体に1つ存在することを示します。一般に、開発者は、静的変数を使用しないことを明示的に指定しない限り、静的変数を使用しないようにする必要があります。

Findステートメントでは、Findを呼び出すときにdelegateキーワードの使用がオプションになりました。デリゲート引数の目的は、リスト内の各項目に対して実行される関数を渡して、trueを返す項目を見つけることです。次のように現代のC#で

、あなたはその行を書くことができます:

Currency result = FindItClass.Find(cur => cur.Code == searchFor); 
関連する問題