我正在使用System.
Windows.Forms.TextBox.根据文档,MaxLength属性控制用户可以键入或粘贴到TextBox中的字符数量(即,可以通过使用例如AppendText函数或Text属性以编程方式添加更多字符).可以从TextLength属性获取当前字符数.
>有没有办法设置最大字符数而不设置自定义限制器,当达到自定义限制时调用Clear()?
>无论如何,它可以容纳的绝对最大值是多少?它只受记忆限制吗?
>达到最大值/内存满时会发生什么?崩溃?顶部x行被清除?
>手动清除前x行的最佳方法是什么?子串操作?
编辑:我测试过它可以容纳超过600k个字符,无论MaxLength如何,此时我手动停止了程序并提出了这个问题.
解决方法
>当然.在派生类中覆盖/隐藏AppendText和Text.见下面的代码.
> Text属性的支持字段是一个普通的旧字符串(私有字段System.Windows.Forms.Control :: text).因此,最大长度是字符串的最大长度,即“2 GB,或大约10亿个字符”(参见 System.String).
>你为什么不尝试看看?
>这取决于您的性能要求.您可以使用Lines属性,但请注意,每次调用它时,您的整个文本都将在内部解析为行.如果你推动内容长度的限制,这将是一个坏主意.因此,更快的方式(在执行方面,而不是编码)将压缩字符并计算cr / lfs.你当然需要决定你在考虑一条线的结尾.
> Text属性的支持字段是一个普通的旧字符串(私有字段System.Windows.Forms.Control :: text).因此,最大长度是字符串的最大长度,即“2 GB,或大约10亿个字符”(参见 System.String).
>你为什么不尝试看看?
>这取决于您的性能要求.您可以使用Lines属性,但请注意,每次调用它时,您的整个文本都将在内部解析为行.如果你推动内容长度的限制,这将是一个坏主意.因此,更快的方式(在执行方面,而不是编码)将压缩字符并计算cr / lfs.你当然需要决定你在考虑一条线的结尾.
代码:即使在以编程方式设置文本时也强制执行MaxLength属性:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication5 {
class TextBoxExt : TextBox {
new public void AppendText(string text) {
if (this.Text.Length == this.MaxLength) {
return;
} else if (this.Text.Length + text.Length > this.MaxLength) {
base.AppendText(text.Substring(0,(this.MaxLength - this.Text.Length)));
} else {
base.AppendText(text);
}
}
public override string Text {
get {
return base.Text;
}
set {
if (!string.IsNullOrEmpty(value) && value.Length > this.MaxLength) {
base.Text = value.Substring(0,this.MaxLength);
} else {
base.Text = value;
}
}
}
// Also: Clearing top X lines with high performance
public void ClearTopLines(int count) {
if (count <= 0) {
return;
} else if (!this.Multiline) {
this.Clear();
return;
}
string txt = this.Text;
int cursor = 0,ixOf = 0,brkLength = 0,brkCount = 0;
while (brkCount < count) {
ixOf = txt.IndexOfBreak(cursor,out brkLength);
if (ixOf < 0) {
this.Clear();
return;
}
cursor = ixOf + brkLength;
brkCount++;
}
this.Text = txt.Substring(cursor);
}
}
public static class StringExt {
public static int IndexOfBreak(this string str,out int length) {
return IndexOfBreak(str,out length);
}
public static int IndexOfBreak(this string str,int startIndex,out int length) {
if (string.IsNullOrEmpty(str)) {
length = 0;
return -1;
}
int ub = str.Length - 1;
int intchr;
if (startIndex > ub) {
throw new ArgumentOutOfRangeException();
}
for (int i = startIndex; i <= ub; i++) {
intchr = str[i];
if (intchr == 0x0D) {
if (i < ub && str[i + 1] == 0x0A) {
length = 2;
} else {
length = 1;
}
return i;
} else if (intchr == 0x0A) {
length = 1;
return i;
}
}
length = 0;
return -1;
}
}
}