C#如何在另一类的索引器中访问Main()方法内的指定元素
实现方案
在C#的索引器、属性的set访问器中,默认提供隐式参数value,代表调用方传入的待赋值内容,你直接用value替换注释位置的占位符即可实现重复值校验。同时建议补充索引类型校验逻辑,避免非数值类型索引传入set块时触发格式转换异常。
修正后的完整类代码如下:
class arrayaccess { private string[] names = new string[] { "carl", "karl", "doe", "john" }; public string this[object index] { get { if (index is string strIndex) { return names.Contains(strIndex) ? "found" : "not found"; } else { byte numIndex = Convert.ToByte(index); if (numIndex >= names.Length) throw new IndexOutOfRangeException("Index should be less than or equal to 3"); return names[numIndex]; } } set { // 直接使用隐式value参数获取传入的待赋值字符串 if (names.Contains(value)) throw new ArgumentException("Sorry, duplicate values not allowed"); // 补充索引类型判断,避免字符串索引传入赋值时报错 if (index is not IConvertible) throw new ArgumentException("Index type is not supported for assignment"); byte numIndex = Convert.ToByte(index); if (numIndex >= names.Length) throw new IndexOutOfRangeException("Index should be less than or equal to 3"); names[numIndex] = value; } } }
效果验证
当你运行Main方法中的aa[3] = "karl"代码时,set访问器会先检测到names数组中已存在值karl,直接抛出你定义的ArgumentException,完全符合需求。
可选优化点
- 可以扩展set块的逻辑,支持字符串类型索引赋值,比如匹配到对应名字的位置时直接更新该位置的值
- 可以将索引数值转换、长度校验的逻辑抽为公共方法,避免get和set块中重复写相同逻辑
内容的提问来源于stack exchange,提问作者Neuser
相关产品推荐
相关产品推荐

