在C#中创建一个简单的名称值映射器类

时间:2009-03-13 16:54:44

标签: c#

我想创建一个简单地将名称映射到值(1到1)的类(静态?)。这样做的干净方法是什么:

public static class FieldMapper
{
  public static GetValue(string Name)
  {
    if (Name == "abc")
        return "Value1";

    if (Name == "def")
        return "Value2";
  }
}

我今天可能会遇到心理障碍。对于像这样的简单问题,我无法想到一个干净的解决方案:(

修改: 所有值在编译时都是已知的(没有唯一性 - 不同的键可以映射到相同的值)。我不应该创建一个在运行时添加值的数据结构。另外,我想避免使用XML文件

6 个答案:

答案 0 :(得分:14)

听起来像是字典的工作。

Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("abc", "Value1");
values.Add("def", "Value2");
Console.WriteLine(values["abc"]);   // Prints "Value1"

答案 1 :(得分:1)

您正在描述Hash Table数据结构。这些通常使用hashing function实现。

C#已经实现了这种类型的数据结构。请参阅IDictionary Interface

答案 2 :(得分:1)

如果您可以将项目预先加载到词典中,那将会有很大帮助:

IDictionary<string, string> myValues = new Dictionary<string, string>( 3 )
{
        {"abc", "Value1"},
        {"def", "Value2"},
        {"ghi", "Value3"}
};

var mySearchString = "abc";
return myValues.Keys.Contains( "abc" ) ? myValues[ mySearchString ] : string.Empty;

答案 3 :(得分:0)

如果您正在讨论在编译时已知的值,您可以尝试将它们存储为资源。像这样:

//Name Spaces Required
using System.Resources;
using System.Reflection;

// Create the resource manager.
Assembly assembly = this.GetType().Assembly;

//ResFile.Strings -> <Namespace>.<ResourceFileName i.e. Strings.resx>
resman = new ResourceManager("StringResources.Strings", assembly);

// Load the value of string value for Client
strClientName = resman.GetString("Client");

(从here被盗)

答案 4 :(得分:0)

我认为字典会更好,但如果你打算在代码中这样做:

 public static class FieldMapper
{  
     public static GetValue(string Name)  
    {    
       switch (Name)
      {
        case "abc":
         return Value1;
      }
    }
}

答案 5 :(得分:0)

如果您希望在编译时而不是在启动时创建集合,则可以使用开关。

如果交换机包含多个项目(五个IIRC),则使用哈希查找实现,因此即使您在其中放入了大量案例,它也非常快。 (即,任何情况下的访问时间都是相同的。)

public static class FieldMapper {

   public static string GetValue(string name) {
      switch (name) {
         case "abc": return "Value1";
         case "def": return "Value2";
      }
      throw new ArgumentException("Unknown name.", "name");
   }
}