C#阻止在类外设置字典属性元素?

时间:2016-12-11 10:37:54

标签: c# properties encapsulation

标题说明了一切。通过访问修饰符减少访问权限只会阻止重新初始化属性;它不会阻止元素成为全局状态(不良做法)。我知道有一个workaround with List<T>'s但是我应该为其他任何索引集合做什么?

public class Start
{
    public static void main()
    {
        //CODE SMELL AHEAD
        AttendanceManager.MuteStatuses[0] = new KeyValuePair <string, string> ("", ""); 
    }
}

public static class AttendanceManager
{ 
    public static HybridDictionary MuteStatuses
    {
        get
        {
            playersMuteStatuses.Add ("", "");
            return playersMuteStatus;
        }
    }      
    private static HybridDictionary playersMuteStatus = new HybridDictionary();
}

2 个答案:

答案 0 :(得分:1)

编写辅助方法:

public static void AddMuteStatus()
    => playersMuteStatus.Add("", "");

public static object GetMuteStatus(object idx)
    => return playersMuteStatus[idx];

答案 1 :(得分:1)

不要使用In [9]: a = 0, *range(10, 12), 2 In [10]: a Out[10]: (0, 10, 11, 2) 。我们有HybridDictionary

IReadOnlyDictionary<T>