C# 防止在 class 之外设置字典 属性 元素?
C# prevent dictionary property elements from being set outside class?
标题说明了一切。通过访问修饰符减少访问只会阻止重新初始化 属性;它不会阻止元素成为全局状态(不良做法)。我知道有一个 workaround with List<T>
's 但我应该为任何其他索引 collection 做什么?
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();
}
编写辅助方法:
public static void AddMuteStatus()
=> playersMuteStatus.Add("", "");
public static object GetMuteStatus(object idx)
=> return playersMuteStatus[idx];
不要使用 HybridDictionary
。我们有 IReadOnlyDictionary<T>
private Dictionary<string, string> playersMuteStatus = new... ;
public IReadOnlyDictionary<string, string> MuteStatuses
{
get
{
return playersMuteStatus as IReadOnlyDictionary<string, string>;
}
}
标题说明了一切。通过访问修饰符减少访问只会阻止重新初始化 属性;它不会阻止元素成为全局状态(不良做法)。我知道有一个 workaround with List<T>
's 但我应该为任何其他索引 collection 做什么?
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();
}
编写辅助方法:
public static void AddMuteStatus()
=> playersMuteStatus.Add("", "");
public static object GetMuteStatus(object idx)
=> return playersMuteStatus[idx];
不要使用 HybridDictionary
。我们有 IReadOnlyDictionary<T>
private Dictionary<string, string> playersMuteStatus = new... ;
public IReadOnlyDictionary<string, string> MuteStatuses
{
get
{
return playersMuteStatus as IReadOnlyDictionary<string, string>;
}
}