c# overriding operator in MyString class returns the same object
本问题已经有最佳答案,请猛点这里访问。
我想重写--mystring类的操作符。它应该在字符串中找到最短的单词。下面是代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | class MyString { private string data; public string Data { get { return data; } set { data = value; } } public MyString(string s) { Data = s; } public MyString(MyString s) { Data = s.Data; } public static MyString operator --(MyString s) { var words = s.Data.Split(); int l = 99999, ind = 0; for (int i = 0; i < words.Length; i++) { if (words[i].Length < l) { ind = i; l = words[i].Length; } } MyString result = new MyString(words[ind]); return result; } } |
当我试图这样使用它时:
1 2 3 4 | MyString s1, shortest; s1 = new MyString("one two three"); shortest = s1--; Console.WriteLine(shortest.Data); |
它返回"一二三"而不是"一"。我怎么修?
1 | var x = foo--; |
是后递减,即类似于:
1 2 | var x = foo; foo--; |
你可能需要预先减刑,也就是说。
1 | var x = --foo; |
类似于:
1 2 | foo--; var x = foo; |
不管怎样:它不适当地改变了
1 2 3 | shortest = --s1; Console.WriteLine(shortest.Data); Console.WriteLine(s1.Data); |
你会看到
我建议改为:
1 2 | shortest = s1.GetShortestWord(); Console.WriteLine(shortest.Data); |