要求模拟string类的部分功能,写一个MyString类,它的部分代码如下所示: class MyString : IComparable { private List chs; public char this[int index] { get { ...... } } } 要求添加代码,使得以下测试函数可执行,每个输出操作的结果如注释所示。除了ToString方法外,其余方法实现时不得使用string类的功能。 static void Main(string[] args) { MyString str1 = new MyString("Hello"); MyString str2 = new MyString("Hello world"); Console.WriteLine(str2.Length);//输出:11 Console.WriteLine(str2[6]);//输出:w Console.WriteLine(str1.ToLower());//输出:hello Console.WriteLine(str1.CompareTo(str2.Substring(0, 5)));//输出:0 Console.WriteLine(str1.CompareTo(str2));//输出:-1 MyString str3 = str1 + new MyString(". Nice to meet you."); Console.WriteLine(str3);//输出:Hello. Nice to meet you. } 解答: using System; using System.Collections; using System.Collections.Generic; using static System.Console; namespace ConsoleApp6 { class MyString : IComparable { private List chs; public char this[int index] { get { if (index < 0 || index >= Length) throw new IndexOutOfRangeException(); return chs[index]; } } public MyString() { chs = new List(); } public MyString(char[] chars) { chs = new List(chars); } public MyString(string str) : this(str.ToCharArray()) { } public int Length { get => chs.Count; } public MyString Substring(int startIndex, int length) { if (startIndex < 0 || startIndex >= Length || Length < 0 || startIndex + length >= Length) throw new IndexOutOfRangeException(); MyString newStr = new MyString(); for (int i = startIndex; i < startIndex + length; i++) { newStr.chs.Add(chs[i]); } return newStr; } public MyString ToLower() { char[] temp = new char[Length]; for (int i = 0; i < chs.Count; i++) { temp[i] = Char.ToLower(chs[i]); } return new MyString(temp); } public static MyString operator+(MyString str1, MyString str2) { str1.chs.AddRange(str2.chs); return str1; } public int CompareTo(MyString other) { if(other == null) throw new ArgumentNullException(); int size = (Length > other.Length) ? other.Length : Length; for (int i = 0; i < chs.Count; i++) { if (chs[i] > other[i]) return 1; else if (chs[i] < other[i]) return -1; } if (Length > other.Length) return 1; else if (Length < other.Length) return -1; else return 0; } public override string ToString() { return new string(chs.ToArray()); } } class Test { static void Main(string[] args) { MyString str1 = new MyString("Hello"); MyString str2 = new MyString("Hello world"); Console.WriteLine(str2.Length);//11 Console.WriteLine(str2[6]);//w Console.WriteLine(str1.ToLower());//hello Console.WriteLine(str1.CompareTo(str2.Substring(0, 5)));//0 Console.WriteLine(str1.CompareTo(str2));//-1 MyString str3 = str1 + new MyString(". Nice to meet you."); Console.WriteLine(str3);//Hello. Nice to meet you. } } }