C#:如何在不将字典公开的情况下浏览字典项?

tes*_*icg 2 c# dictionary

该课程如下:

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;
        }
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

也应该使用ReaderWriterLockSlim锁定器对象.

客户端现在看起来如下:

foreach (KeyValuePair<string, object> dictItem in CacheManager.CacheItems)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

先感谢您.

Mar*_*ell 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]; } }
Run Code Online (Sandbox Code Playgroud)