将 .NET StreamWriter 输出重定向到 String 变量

发布于 2024-07-07 11:42:47 字数 268 浏览 7 评论 0原文

我想知道是否可以将 StreamWriter 输出重定向到变量,

例如

String^ myString;
StreamWriter sw = gcnew StreamWriter([somehow specify myString])
sw->WriteLine("Foo");

myString 将包含 Foo。 我想这样做的原因是重用一个复杂的函数。 我可能应该将其重构为字符串返回函数,但知道它仍然是一个很好的技巧

I'd like to know if it is possible to redirect StreamWriter output to a variable

Something like

String^ myString;
StreamWriter sw = gcnew StreamWriter([somehow specify myString])
sw->WriteLine("Foo");

then myString will contain Foo.
The reason I would like to do this is to reuse a complex function. I should probably refactor it into a String returning function but it still would be a nice hack to know

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

听风吹 2024-07-14 11:42:47

您可以使用 StringWriter 将值直接写入字符串构建器对象来完成此操作

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
// now, the StringWriter instance 'sw' will write to 'sb'

You can do this with a StringWriter writing the value directly to a string builder object

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
// now, the StringWriter instance 'sw' will write to 'sb'
陈年往事 2024-07-14 11:42:47

StreamWriterStringWriter 都扩展了 TextWriter,也许您可​​以重构使用 StreamWriter 的方法来使用 TextWriter,这样它可以写入流或字符串吗?

StreamWriter and StringWriter both extend TextWriter, perhaps you could refactor your method that uses StreamWriter to use TextWriter instead so it could write to either a stream or a string?

夜夜流光相皎洁 2024-07-14 11:42:47

您应该能够使用内存流执行您需要的操作。

MemoryStream mem = new MemoryStream(); 
StreamWriter sw = new StreamWriter(mem);
sw.WriteLine("Foo"); 
// then later you should be able to get your string.
// this is in c# but I am certain you can do something of the sort in C++
String result = System.Text.Encoding.UTF8.GetString(mem.ToArray(), 0, (int) mem.Length);

You should be able to do what you need using a Memory Stream.

MemoryStream mem = new MemoryStream(); 
StreamWriter sw = new StreamWriter(mem);
sw.WriteLine("Foo"); 
// then later you should be able to get your string.
// this is in c# but I am certain you can do something of the sort in C++
String result = System.Text.Encoding.UTF8.GetString(mem.ToArray(), 0, (int) mem.Length);
橘虞初梦 2024-07-14 11:42:47

正如您提到的那样,重构该方法以返回字符串。 按照您尝试的方式进行黑客攻击,虽然在学术上很有趣,但会使代码变得混乱,并使跟随您的人很难维护。

Refactor the method to return string as you mentioned you could. Hacking it the way you are attempting, while academically interesting, will muddy the code and make it very hard to maintain for anyone that follows you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文