C#/.NET 泛型+索引器搭建通用字典Dictionary
阿新 • • 發佈:2019-01-09
C#/.NET 泛型+索引器搭建通用字典Dictionary
public enum Types { X, Y, Z, W } public class DemoInfoMap<T> { private Dictionary<Types, T> demoMap = new Dictionary<Types, T>(); public DemoInfoMap() { this.demoMap.Add(Types.X, default(T)); this.demoMap.Add(Types.Y, default(T)); this.demoMap.Add(Types.Z, default(T)); this.demoMap.Add(Types.W, default(T)); } //索引器引數需跟字典的key一樣 public T this[Types axis] { get { return this.demoMap[axis]; } set { this.demoMap[axis] = value; } } public DemoInfoMap<UInt32> DemoInfo { get { var demoInfo = new DemoInfoMap<UInt32>(); demoInfo[Types.X] = 2; return demoInfo; } } }
呼叫
public DemoInfoMap<UInt32> DemoStatusInfo
{
get
{
var statusInfo = new DemoInfoMap<UInt32>();
statusInfo[Types.X] = 2;
return statusInfo;
}
}
public void DemoControl()
{
var index = DemoStatusInfo[Types.X];
}