我可以序列C#类型的对象? [英] Can I serialize a C# Type object?
问题描述
我想序列化以下列方式Type对象:
I'm trying to serialize a Type object in the following way:
Type myType = typeof (StringBuilder);
var serializer = new XmlSerializer(typeof(Type));
TextWriter writer = new StringWriter();
serializer.Serialize(writer, myType);
当我这样做,以序列化调用抛出以下异常:
When I do this, the call to Serialize throws the following exception:
是没有预料到的类型System.Text.StringBuilder。使用
XmlInclude或SoapInclude属性来指定不属于
静态已知类型。
"The type System.Text.StringBuilder was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."
有我的方式来序列化键入
对象吗?请注意,我不是要序列化的StringBuilder
本身,而是键入
包含有关的元数据对象的StringBuilder
类。
Is there a way for me to serialize the Type
object? Note that I am not trying to serialize the StringBuilder
itself, but the Type
object containing the metadata about the StringBuilder
class.
推荐答案
我不知道,一个Type对象可以创建仅包含完全限定名称的字符串。要获得完全合格的名称,可以使用以下内容:
I wasn't aware that a Type object could be created with only a string containing the fully-qualified name. To get the fully qualified name, you can use the following:
string typeName = typeof (StringBuilder).FullName;
您可以再坚持这个字符串但是必须的,那么重建这样的类型:
You can then persist this string however needed, then reconstruct the type like this:
Type t = Type.GetType(typeName);
如果您需要创建类型的实例,你可以这样做:
If you need to create an instance of the type, you can do this:
object o = Activator.CreateInstance(t);
如果您检查o.GetType()的值,这将是StringBuilder的,就像你期望。
If you check the value of o.GetType(), it will be StringBuilder, just as you would expect.
这篇关于我可以序列C#类型的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!