C# 我可以在 foreach 中使用 StringBuilder 元素吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14818139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I use StringBuilder elements in a foreach?
提问by B. Clay Shannon
Since I'm using .NET 1.1, I can't use a generic List of string, as generics were not part of the language yet. So I'm trying to use a StringBuilder, but get this err msg:
由于我使用的是 .NET 1.1,我不能使用字符串的泛型列表,因为泛型还不是语言的一部分。所以我正在尝试使用 StringBuilder,但得到这个错误消息:
"foreach statement cannot operate on variables of type 'System.Text.StringBuilder' because 'System.Text.StringBuilder' does not contain a definition for 'GetEnumerator', or it is inaccessible"
“foreach 语句不能对'System.Text.StringBuilder' 类型的变量进行操作,因为'System.Text.StringBuilder' 不包含'GetEnumerator' 的定义,或者它是不可访问的”
with this code:
使用此代码:
public StringBuilder linesToSend;
. . .
foreach (string _line in this.linesToSend)
{
serialPort.Write(_line);
}
Is there something wrong with my code, or is StringBuilder really disallowed from foreach loops? If the latter, is String[] my best recourse?
我的代码有问题吗,或者 StringBuilder 真的不允许在 foreach 循环中使用?如果是后者,String[] 是我最好的追索权吗?
采纳答案by Justin Niessner
A StringBuilder
doesn't store the lines that you append. It simply is used to build the final string. Assuming you've added everything to the StringBuilder
already, you can do:
AStringBuilder
不存储您附加的行。它仅用于构建最终字符串。假设您已经将所有内容添加到了StringBuilder
,您可以执行以下操作:
// Write the complete string to the serialPort
serialPort.Write(linesToSend.ToString());
回答by Jeppe Stig Nielsen
A StringBuilder
is building just onestring, so how could you foreach
it to get a whole sequence of strings?
AStringBuilder
只构建一个字符串,那么你怎么能foreach
得到一个完整的字符串序列呢?
If you need to write line by line, maybe use an ArrayList
, add each line string to that, and foreach
with string
as the foreach
variable type (Object
will be cast to String
). Or even better, use StringCollection
(thank to comment by Anthony Pegram, to the original question; I had forgotten this class).
如果您需要逐行编写,可以使用ArrayList
,将每一行字符串添加到其中,并将foreach
withstring
作为foreach
变量类型(Object
将被强制转换为String
)。或者甚至更好,使用StringCollection
(感谢 Anthony Pegram 对原始问题的评论;我忘记了这门课)。
But why not upgrade to a newer version of .NET?
但为什么不升级到更新版本的 .NET?
回答by Joshua
This is correct. A StringBuilder
is designed to help you build one final output string as the others have stated.
这是对的。AStringBuilder
旨在帮助您构建一个最终输出字符串,如其他字符串所述。
If you have a variable number of strings you need to work on, you can use an ArrayList
and iterate over that.
如果您需要处理可变数量的字符串,则可以使用 anArrayList
并对其进行迭代。
ArrayList strings = new ArrayList();
// populate the list
foreach (string str in strings) {
// do what you need to.
}
If you're afraid that the array list might contain other objects (as it isn't strongly typed) you can cast it safely instead:
如果您担心数组列表可能包含其他对象(因为它不是强类型的),您可以安全地转换它:
foreach (object obj in strings) {
string str = obj as string;
// If null strings aren't allowed, you can use the following
// to skip to the next element.
if (str == null) {
continue;
}
}
回答by Dustin Kingen
The foreach
loop works by calling the GetEnumerator
from the interface IEnumerable
which will return an enumerator that foreach
uses to get the next element of the object.
该foreach
循环通过GetEnumerator
从接口调用 来工作,该接口IEnumerable
将返回一个枚举器,foreach
用于获取对象的下一个元素。
StringBuilder
does not implement IEnumerable
or IEnumerable<T>
which would allow the foreach
to work. You are better off using a string[]
or StringCollection
in this case and when you are done you can concatenate the collection using a StringBuilder
.
StringBuilder
不实施IEnumerable
或IEnumerable<T>
将允许foreach
工作。在这种情况下,您最好使用 astring[]
或StringCollection
,完成后您可以使用 a 连接集合StringBuilder
。
ex:
前任:
StringBuilder stringBuilder = new StringBuilder();
foreach(string line in array)
{
serialPort.Write(line);
stringBuilder.Append(line);
}
回答by Captain Kenpachi
What you're looking for is an array of strings if you know the number of elements, or else a dictionary.
如果您知道元素的数量,您正在寻找的是一个字符串数组,或者是一个字典。
回答by Jason McKindly
Old question, I know, but something potentially useful:
老问题,我知道,但一些可能有用的东西:
If each of your strings were built with .AppendLine or you inserted a new line, you can do
如果你的每个字符串都是用 .AppendLine 构建的,或者你插入了一个新行,你可以这样做
string[] delim = { Environment.NewLine, "\n" }; // "\n" added in case you manually appended a newline
string[] lines = StringBuilder.ToString().Split(delim, StringSplitOptions.None);
foreach(string line in lines){
// Do something
}