1

我确信我不会使用正确的词语来解释,但我希望你能理解我想要完成的事情。我有一个在字典集合中传递的类。传入的字典集合是否必须具有此类所需的某些键。我希望能够公开公开课程所需的那些密钥,但不仅仅是字符串,而是实际项目。枚举会起作用,但由于这个类是一个基类,我认为这不是一个好的解决方案。我需要类似于每次将项目添加到 Resources.resx 文件时生成的 Resources 类。所以你可以去 Resources.Resources.MyLabel1、Resources.Resources.MyLabel2 等。这可能吗?

谢谢,迈克

4

3 回答 3

2

Create properties that expose your values

public class MyClass

    private Dictionary<string,string> _dict;

    public MyClass (Dictionary<string,string> dict)
    {
        _dict = dict;
    }

    public string FirstName { get { return _dict["FirstName"]; } }
    public string LastName { get { return _dict["LastName"]; } }
    ...
}

Alternatively you can aslo create read/write properties

public string FirstName { 
    get { return _dict["FirstName"]; }
    set { _dict["FirstName"] = value; }
}
于 2012-06-20T16:46:05.310 回答
1

你可以在你的类上提供一个 static 或 const 成员:

class PickyClass {
  public static readonly string[] RequiredKeys = new[] {"length", "width"};

  /// <summary>
  /// Please note that you must include at least RequiredKeys in values
  /// </summary>
  public void Setup(Dictionary<string,string> values)
  {
    ...
  }
}

(编辑)还是按名称可寻址它们很重要?在这种情况下,如何:

class PickyClass {
  public class RequiredKeys
  {
    public const string Length = "length";
    public const string Width = "width";
  }

  /// <summary>
  /// Please note that you must include every const in RequiredKeys in values
  /// </summary>
  public void Setup(Dictionary<string,string> values)
  {
    ...
  }
}
于 2012-06-20T16:39:22.093 回答
0

这听起来像是你应该隐藏的细节

public void Setup(Dictionary<string,string> values)

如果values必须包含某些键,那么也许您可以将该信息编码为您自己的字典类型。

public class FussyDictionary : Dictionary<string,string> {
  // You must provide these values
  public FussyDictionary(string valueA, string valueB) {
     Add("magicKey1", valueA);
     Add("magicKey2", valueB);
  }

  // Override remove to stop you removing these keys?
}
于 2012-06-20T16:46:54.123 回答