c#

小菜鸡coding 2021-04-07 10:46:32
创建一个可以存储整数、字符串的类List,其最大容量为100。List类由以下成员构成: ①私有常量字段Max,用于表示存储的最大元素数目; ②私有字段num,用于表示当前实际元素个数; ③私有object类型数组listArray,用于存储整型、字符串数据; ④公有方法add(object obj),用于将元素obj添加到listArray末尾; ⑤公有方法delete(int pos),用于删除位置为pos的元素; ⑥公有方法get(int pos),用于获取指定位置pos的元素; ⑦公有方法getnum(),用于获取实际元素个数; ⑧公有方法disp(),其功能是显示所有元素。 请根据要求定义类List并进行测试。 这个题目怎么做啊?
...全文
254 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Hello World, 2021-04-08
  • 打赏
  • 举报
回复
跑错地方了,该去C#版的。 示例: 定义: [code=c#] class List { private readonly int Max = 100; private int Num { get { return listArray.Count(); } } private readonly List<object> listArray = new List<object>(); public int Add(object obj) { if (obj.GetType() != typeof(int) && obj.GetType() != typeof(string)) { throw new ArgumentException("参数类型不正确"); } if (Num >= Max) throw new ArgumentOutOfRangeException("元素个数超过允许的范围"); listArray.Add(obj); return Num; } public int Delete(int index) { if (index < 0 || index > Num - 1) throw new IndexOutOfRangeException("索引不在范围内"); listArray.RemoveAt(index); return Num; } public object Get(int index) { if (index < 0 || index > Num - 1) throw new IndexOutOfRangeException("索引不在范围内"); return listArray.ElementAt(index); } public int Getnum() { return Num; } public void Disp() { listArray.ForEach(item => Console.WriteLine(item)); } } [/code] 调用: [code=c#] try { var list = new List(); for (var i = 0; i < 50; i++) { list.Add(i); } Console.WriteLine($"当前元素个数为:{list.Getnum()}"); for (var i = 0; i < 50; i++) { list.Add("string" + i.ToString()); } Console.WriteLine($"当前元素个数为:{list.Getnum()}"); list.Disp(); Console.WriteLine($"第10个元素是{list.Get(9)}"); list.Delete(10); Console.WriteLine($"当前元素个数为:{list.Getnum()}"); list.Add(100); list.Add("100"); } catch (Exception ex) { Console.WriteLine(ex.Message); } [/code]

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧