我正在努力学习和实践 OOP 原则,我需要一些帮助来帮助我克服困难。我有以下代码:
using System.Collections.Generic;
namespace Test
{
class Program
{
static void Main()
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("cat", "one");
dictionary.Add("dog", "two");
dictionary.Add("llama", "three");
dictionary.Add("iguana", "four");
var test1 = GetKVP(dictionary, "llama");
var test2 = GetValue(dictionary, "llama");
var test3 = GetPosition(dictionary, "llama");
}
static KeyValuePair<string, string> GetKVP(Dictionary<string, string> dict, string key_to_find)
{
foreach (KeyValuePair<string, string> kvp in dict)
{
if (kvp.Key == key_to_find)
{return kvp;}
}
return new KeyValuePair<string, string>();
}
static string GetValue(Dictionary<string, string> dict, string key_to_find)
{
foreach (KeyValuePair<string, string> kvp in dict)
{
if (kvp.Key == key_to_find)
{return kvp.Value;}
}
return string.Empty;
}
static int GetPosition(Dictionary<string, string> dict, string key_to_find)
{
int counter = 0;
foreach (KeyValuePair<string, string> kvp in dict)
{
if (kvp.Key == key_to_find)
{return counter;}
counter += 1;
}
return -1;
}
}
}
我想要做的是整合代码集,这样我就可以有一个方法来返回不同的数据类型而无需重复代码。 请不要评论有几种更有效的方法来搜索字典这一事实,我知道这并不理想。我只是模拟了一些数据和方法以用作示例。对于我的生活,我真的无法想象如何实现这样的东西。