【问题标题】:How to return reference to non-modifiable object in C#如何在 C# 中返回对不可修改对象的引用
【发布时间】:2014-01-27 08:22:00
【问题描述】:

我有这样的课:

static private Dictionary<int, String> states;

static public Dictionary<int, String> GetStates()
{
  if (states != null)
  {
    return states;
  }
  else
  {
    states = new Dictionary<int, string>();
    states.Add(1, "State 1 name.");
    states.Add(2, "State 2 name");
    // etc
  }
  return states;
}

返回的字典应该是不可修改的。 寻找解决此问题的最佳方法。

【问题讨论】:

标签: c# object reference return


【解决方案1】:

如果您将返回类型更改为IDictionary&lt;TKey, TValue&gt;,那么您应该能够返回ReadOnlyDictionary

static public IDictionary<int, String> GetStates()
{
  if (states != null)
  {
    return new ReadOnlyDictionary(states);
  }

【讨论】:

  • 明确地说,您可以将返回类型更改为IReadOnlyDictionary&lt;TKey, TValue&gt;
猜你喜欢
  • 2019-05-13
  • 2017-05-03
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多