简体   繁体   English

高效使用TextWriter

[英]Efficient usage of TextWriter

Is there any alternative way to perform the operation: 是否有其他方法可以执行该操作:

textWriter.Write(myBigObject.ToString())

such that: 这样:

  • myBigObject is 'streamed' into the text representation without creating the whole string object in memory myBigObject被“流化”为文本表示形式,而无需在内存中创建整个字符串对象
  • there are no additional classes or objects used, beside myBigObject and textWriter 除了myBigObjecttextWriter之外,没有使用其他类或对象

Example: Imagine that myBigObject has 50 string fields. 示例:假设myBigObject有50个字符串字段。 There is no point in joining all these fields in a big string and then writing the object to a file, if it is somehow possible to write the strings one by one to the file. 如果可以通过某种方式将字符串一个接一个地写入文件,那么将所有这些字段合并成一个大字符串然后将对象写入文件是没有意义的。

If you have access to the code, you can add a method to MyBigObject that takes a TextWriter and writes out each property. 如果可以访问代码,则可以向MyBigObject添加一个方法,该方法采用TextWriter并写出每个属性。 For example: 例如:

public class MyBigObject
{
    public void Write(TextWriter writer)
    {
        writer.Write(bigStringField1);
        writer.Write(bigStringField2);
        // etc.
    }
}

If sub-classes of MyBigObject need to write their own representation, then make the method virtual, and the sub-classes call the implementation in the base class. 如果MyBigObject子类需要编写自己的表示形式,则使该方法为虚拟方法,然后这些子类在基类中调用实现。

If you don't own the code, and the fields are exposed through properties, you could build an adapter class that takes a MyBigObject and writes out each property. 如果您不拥有代码,并且这些字段通过属性公开,则可以构建一个适配器类,该适配器类使用MyBigObject并写出每个属性。 You could also build some extension methods that do the same thing. 您还可以构建一些执行相同操作的扩展方法。

If you cannot access the source code, you could use reflection to do examine the fields on the object, grab the value of each field, and Write() out each value's ToString() representation. 如果您无法访问源代码,则可以使用反射来检查对象上的字段,获取每个字段的值,然后对每个值的ToString()表示形式进行Write() However, reflection is slower than direct field access, and it involves a lot more intermediate objects. 但是,反射比直接字段访问要慢,并且涉及更多的中间对象。 I don't know if using reflection would be worth it in your case. 我不知道在您的情况下使用反射是否值得。

Given the limitations you have outlined this isn't possible. 鉴于您所概述的限制,这是不可能的。 You would have to come up with a way to read the data from your object and write it out on char/byte/line at a time. 您将不得不想出一种从对象中读取数据并将其一次写出到char / byte / line上的方法。

If you want to be able to loop over your properties and write them out one at a time then this would be possible using reflection . 如果您希望能够遍历属性并一次将其写出,那么可以使用反射来实现。 However I suspect going this route would result in using more memory than your original solution as well as being much more complicated than a simple call to .ToString(). 但是,我怀疑走这条路线会导致比原始解决方案使用更多的内存,并且比对.ToString()的简单调用要复杂得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM