关于xmlTextWriter的小问题 [英] trivial doubt about the xmlTextWriter

查看:178
本文介绍了关于xmlTextWriter的小问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class SerializeManager<T> {
	public string SerializeObject(T pObject) { 
		string XmlizedString = null; 
		MemoryStream memoryStream = new MemoryStream(); 
		XmlSerializer xs = new XmlSerializer(typeof(T)); 
		XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); 
		xs.Serialize(xmlTextWriter, pObject); 
        //???-------here---------???//
		memoryStream = (MemoryStream)xmlTextWriter.BaseStream; 

		XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray()); 
		return XmlizedString; 
	} 





我只是不明白这一行:



I just don't understand about this line:

memoryStream = (MemoryStream)xmlTextWriter.BaseStream





在我看来,因为他指定了 memoryStream XmlTextWriter 构造函数中。

只是一个冗余。



真的吗?



in my opinion,because he has specified memoryStream in XmlTextWriter constuctor.
that is only a redundancy.

really?

推荐答案

XmlTextWriter.BaseStream属于Stream类型。



虽然MemoryStream为此目的继承了Stream和'is'Stream,但它是如果没有其他原因那么可读性仍然是一个好主意。



此外,你在输出中收到警告(如果你有治疗警告,甚至会出错)当错误打开时)
XmlTextWriter.BaseStream is of type Stream.

While MemoryStream inherits Stream and 'is' Stream for this purpose, it is still good idea to explicitly cast it, if for no other reason then readability.

Also, you get a warning in the output (or even error if you have treat warnings as errors turned on)


这是必需的。您将MemoryStream传递给构造函数,但它存储为Stream,换句话说,它是从MemoryStream下载到Stream。同样,BaseStream返回Stream类型。即使对象BaseStream返回的是MemoryStream,您也必须将其向上转换回MemoryStream,因为您知道它是一个内存流。如果不将其转发回MemoryStream,您将无法访问ToArray,因为它不在基础Stream类上。此外,如果没有显式强制转换,代码将无法编译,因为您无法从Stream隐式转换为MemoryStream。这些是相当标准的基于继承的问题。在处理支持泛型的类时,您会发现这些问题较少,因为您总是在处理正确的类型。
It is required. You passed a MemoryStream into the constructor but that is stored as "Stream", in other words it is down-casted from MemoryStream to Stream. Likewise the BaseStream returns type Stream. Even though the object BaseStream returns is MemoryStream, you have to "up cast" it back to MemoryStream as you know it is a memory stream. Without casting it back to MemoryStream you won't have access to ToArray, as that is not on the underlying Stream class. Also without the explicit cast the code won't compile as you can't implicitly convert from from Stream to MemoryStream. These are fairly standard inheritance-based issues. You see less of these issues when dealing with classes that support generics as you're always dealing with the correct types.


这篇关于关于xmlTextWriter的小问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆