如何创建带自定义LowerBound的HouseInfo类型C#数组?
实现自定义下界的强类型数组
有两种简便方式解决这个问题:
方式一:直接使用GetValue/SetValue方法
Array基类虽未提供强类型索引器,但内置了GetValue和SetValue方法用于元素访问,可直接用来操作自定义下界数组:
// 创建自定义下界数组 Array houses = Array.CreateInstance(typeof(HouseInfo), numberOfHouses, lowestHouseNumber); // 设置元素 houses.SetValue(new HouseInfo(), 1022); // 获取元素 HouseInfo house = (HouseInfo)houses.GetValue(1022);
这种方式无需额外封装,适合简单场景快速使用。
方式二:封装强类型自定义下界数组类
如果希望像普通数组一样通过[]索引器访问,可以封装一个类来包装Array实例,提供强类型索引器:
public class CustomLowerBoundArray<T> { private readonly Array _innerArray; public CustomLowerBoundArray(int length, int lowerBound) { _innerArray = Array.CreateInstance(typeof(T), length, lowerBound); LowerBound = lowerBound; UpperBound = lowerBound + length - 1; } public int LowerBound { get; } public int UpperBound { get; } public T this[int index] { get => (T)_innerArray.GetValue(index); set => _innerArray.SetValue(value, index); } }
使用时和普通数组体验一致:
var houses = new CustomLowerBoundArray<HouseInfo>(numberOfHouses, lowestHouseNumber); houses[1022] = new HouseInfo(); HouseInfo firstHouse = houses[1022];
补充说明
普通一维数组(如int[])能直接用[]索引,是因为它们是CLR提供的具体化数组类型,这类类型会自动实现强类型索引器。而Array.CreateInstance创建的是通用Array实例,没有内置强类型索引器,因此需要通过上述两种方式实现强类型访问。
内容的提问来源于stack exchange,提问作者Ghassan Karwchan
相关产品推荐
相关产品推荐

