将 .NET StreamWriter 输出重定向到 String 变量
我想知道是否可以将 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 StringWriter 将值直接写入字符串构建器对象来完成此操作
You can do this with a StringWriter writing the value directly to a string builder object
StreamWriter 和 StringWriter 都扩展了 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?
您应该能够使用内存流执行您需要的操作。
You should be able to do what you need using a Memory Stream.
正如您提到的那样,重构该方法以返回字符串。 按照您尝试的方式进行黑客攻击,虽然在学术上很有趣,但会使代码变得混乱,并使跟随您的人很难维护。
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.