このプロパティはどうですか:
public static IEnumerable<KeyValuePair<string, object> CacheItems
{
get
{
return cacheItems;
}
}
ディクショナリは 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);
}
}