Testing for Dictionary KeyNotFoundException

后端 未结 4 637
猫巷女王i
猫巷女王i 2021-01-26 09:51

I have a scenario where there is a dictionary that might or might not have a key value at a given time. I am presently testing to see if the value exists in the following manner

4条回答
  •  独厮守ぢ
    2021-01-26 10:25

    Here is an example for you

     using System;
     using System.Collections.Generic;
    
    class Program
    {
     static void Main()
     {
      Dictionary test = new Dictionary();
      test.Add("one", "value");
    //
    // Use TryGetValue to avoid KeyNotFoundException.
    //
    string value;
    if (test.TryGetValue("two", out value))
    {
        Console.WriteLine("Found");
    }
    else
    {
        Console.WriteLine("Not found");
    }
      }
    }
    

提交回复
热议问题