我正在编写一个简单的结构来模拟字符串数组,但添加了一些实用的操作符和其他我想在字符串中看到的函数。 特别是我现在要处理的方法是 / 操作符。
问题是,它不会像我想要的那样,在末尾添加任何余数。它应该做的是,取一个字符串数组,例如:{"Hello", "Test1", "Test2", "Goodbye", "More?", "Qwerty"},如果我想除以4,它应该返回 {"Hello","Test1","Test2","Goodbye"},{"More?","Qwerty"},但它没有。
整个类(我希望改进的方法是 / 操作符,但如果你有其他想法,请指出)(我知道几乎没有注释。 对此很抱歉,我没有想到其他人除了我会查看这段代码。):
public struct StringCollection
{
private String[] value;
public StringCollection(params String[] s)
{
this.value = s;
}
public StringCollection(StringCollection current, String ad)
{
if (current.value == null) {
current.value = new String[0] { };
}
this.value = new String[current.value.Length+1];
for (int i=0; i<this.value.Length; i++)
{
try {
this.value[i] = current[i];
} catch {
break;
}
}
this.value[this.value.Length-1] = ad;
}
public StringCollection(StringCollection x, params StringCollection[] y)
{
this.value = x.value;
for (int j=0;j<y.Length;j++)
{
for (int i=0;i<y[j].value.Length;i++)
{
this += y[j][i];
}
}
}
public static StringCollection[] operator /(StringCollection x, int y)
{
StringCollection[] result = null;
if (((int)x.value.Length/y) == ((double)x.value.Length)/y)
result = new StringCollection[y];
else
result = new StringCollection[y+1];
for (int j=0;j<y;j++)
{
for (int i=0;i<((int)x.value.Length/y);i++)
{
result[j] += x.value[i+(int)((x.value.Length/y)*j)];
}
}
if (((int)x.value.Length/y) != ((double)x.value.Length)/y)
{
// This is the part that isn't working.
for (int i=0;i<(((int)x.value.Length/y)*result[0].value.Length)-x.value.Length;i++)
{
result[result.Length-1] += x.value[i+((result[0].value.Length)*result.Length-2)];
}
}
return result;
}
public String this[int index]
{
get {
return this.value[index];
}
set {
this.value[index] = value;
}
}
}
它的作用基本上是将你的数组(单个数组)分成一堆大小相同的数组,然后在末尾添加余数组成一个新的数组。
StringCollection
构造和/
操作方法即可。 - IAbstractStringCollection
类?它看起来像是一个非标准的、笨重的、低效的实现,而且已经有了一个相当好用的List<string>
。你可以编写一个静态的帮助方法来执行“分组”操作。我不怀疑你需要进行分组操作,但是在我的看法中,重载“/”来表示它是一个可怕的设计决策。将其命名为GetGroupsOf
或类似的名称。返回值应该是List<List<string>>
类型。 - Jim Mischel