Can I serialize a C# Type object?

前端 未结 6 1559
南方客
南方客 2020-12-04 17:18

I\'m trying to serialize a Type object in the following way:

Type myType = typeof (StringBuilder);
var serializer = new XmlSerializer(typeof(Type));
TextWrit         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 18:01

    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);
    

    If you check the value of o.GetType(), it will be StringBuilder, just as you would expect.

提交回复
热议问题