我可以序列化C#类型对象吗?
时间:2020-03-05 18:39:53 来源:igfitidea点击:
我正在尝试通过以下方式序列化Type对象:
Type myType = typeof (StringBuilder); var serializer = new XmlSerializer(typeof(Type)); TextWriter writer = new StringWriter(); serializer.Serialize(writer, myType);
当我这样做时,对Serialize的调用将引发以下异常:
"The type System.Text.StringBuilder was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."
我有办法序列化"类型"对象吗?注意,我不是在尝试序列化StringBuilder本身,而是在Type对象中包含关于StringBuilder类的元数据。
解决方案
回答
只看它的定义,它没有标记为Serializable。如果我们确实需要将此数据进行序列化,则可能必须将其转换为标记为此类的自定义类。
public abstract class Type : System.Reflection.MemberInfo Member of System Summary: Represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types. Attributes: [System.Runtime.InteropServices.ClassInterfaceAttribute(0), System.Runtime.InteropServices.ComDefaultInterfaceAttribute(System.Runtime.InteropServices._Type), System.Runtime.InteropServices.ComVisibleAttribute(true)]
回答
根据System.Type [1]的MSDN文档,我们应该能够序列化System.Type对象。但是,由于该错误明确地指向System.Text.StringBuilder,因此很可能是导致序列化错误的类。
[1]类型类(系统)http://msdn.microsoft.com/zh-cn/library/system.type.aspx
回答
我不知道只能使用包含完全限定名称的字符串来创建Type对象。要获取标准名称,可以使用以下命令:
string typeName = typeof (StringBuilder).FullName;
然后,我们可以根据需要持久化此字符串,然后像这样重构类型:
Type t = Type.GetType(typeName);
如果需要创建该类型的实例,则可以执行以下操作:
object o = Activator.CreateInstance(t);
如果我们检查o.GetType()的值,则它将是StringBuilder,正如我们所期望的那样。