2

クラスは次のようになります。

public static class CacheManager
{
    private static Dictionary<string, object> cacheItems = new Dictionary<string, object>();

    private static ReaderWriterLockSlim locker = new ReaderWriterLockSlim();

    public static Dictionary<string, object> CacheItems
    {
        get
        {
            return cacheItems;
        }
    }
    ...
}

ReaderWriterLockSlim ロッカー オブジェクトも使用する必要があります。

クライアントは次のようになります。

foreach (KeyValuePair<string, object> dictItem in CacheManager.CacheItems)
{
    ...
}

前もって感謝します。

4

4 に答える 4

6

コンテンツを反復するだけでよい場合、率直に言って、実際には辞書として使用されているわけではありませんが、反復子ブロックとインデクサーを使用して内部オブジェクトを非表示にすることができます。

public IEnumerable<KeyValuePair<string, object>> CacheItems
{
    get
    { // we are not exposing the raw dictionary now
        foreach(var item in cacheItems) yield return item;
    }
}
public object this[string key] { get { return cacheItems[key]; } }
于 2012-06-14T07:51:44.780 に答える
3

このプロパティはどうですか:

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);
    }
}
于 2012-06-14T07:39:58.013 に答える
1

フィルタリングするディクショナリの読み取り専用ビューであるプロパティを公開しますか?アイテムへのアクセスを可能な限り許可するメソッドを公開します。

正確には何が問題ですか?「辞書を公開せずに」というのは漠然としていて、答えられないほどです。

于 2012-06-14T07:37:42.180 に答える
0

辞書のサイズによっては、MemberwiseCloneを使用できます。

また、 IsReadOnlyプロパティを調べることもできます。

于 2012-06-14T08:01:42.353 に答える