这个楼盘怎么样:
public static IEnumerable<KeyValuePair<string, object> CacheItems
{
get
{
return cacheItems;
}
}
Dictionary 实现了 IEnumerable 接口(您的 foreach 语句已经使用了该接口),但是通过仅将其真正公开为 IEnumerable 您可以防止向字典添加或删除项目的任何可能性。
如果您需要通过索引运算符访问字典,您可以很容易地实现 ReadOnlyDictionary。然后它看起来像这样:
public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private IDictionary<TKey, TValue> _Source;
public ReadOnlyDictionary(IDictionary<TKey, TValue> source)
{
if(source == null)
throw new ArgumentNullException("source");
_Source = source;
}
// ToDo: Implement all methods of IDictionary and simply forward
// anything to the _Source, except the Add, Remove, etc. methods
// will directly throw an NotSupportedException.
}
在这种情况下,您还可以将缓存传播为
private static ReadOnlyDictionary<string, object> _CacheReadOnly;
private static Dictionary<string, object> _CacheItems;
public static ctor()
{
_CacheItems = new Dictionary<string, object>();
_CacheReadOnly = new ReadOnlyDictionary(_CacheItems);
}
public static IDictionary<string, object> CacheItems
{
get
{
return CacheReadOnly;
}
}
更新
如果你真的需要阻止转换回 Dictionary 你也可以使用这个:
public static IEnumerable<KeyValuePair<string, object> CacheItems
{
get
{
return cacheItems.Select(x => x);
}
}