Posso serializar um objeto tipo C#?
-
08-06-2019 - |
Pergunta
Estou tentando serializar um objeto Type da seguinte maneira:
Type myType = typeof (StringBuilder);
var serializer = new XmlSerializer(typeof(Type));
TextWriter writer = new StringWriter();
serializer.Serialize(writer, myType);
Quando faço isso, a chamada para Serialize gera a seguinte exceção:
"O tipo System.Text.StringBuilder não era esperado.Use o atributo xmlinclude ou sabão para especificar tipos que não são conhecidos estaticamente ".
Existe uma maneira de serializar o Type
objeto?Observe que não estou tentando serializar o StringBuilder
em si, mas o Type
objeto que contém os metadados sobre o StringBuilder
aula.
Solução
Eu não sabia que um objeto Type poderia ser criado apenas com uma string contendo o nome totalmente qualificado.Para obter o nome totalmente qualificado, você pode usar o seguinte:
string typeName = typeof (StringBuilder).FullName;
Você pode então persistir essa string conforme necessário e reconstruir o tipo assim:
Type t = Type.GetType(typeName);
Se precisar criar uma instância do tipo, você pode fazer o seguinte:
object o = Activator.CreateInstance(t);
Se você verificar o valor de o.GetType(), será StringBuilder, exatamente como seria de esperar.
Outras dicas
Eu tive o mesmo problema e minha solução foi criar uma classe SerializableType.Ele converte livremente de e para System.Type, mas serializa como uma string.Tudo que você precisa fazer é declarar a variável como SerializableType e, a partir de então, você pode se referir a ela como System.Type.
Aqui está a aula:
// a version of System.Type that can be serialized
[DataContract]
public class SerializableType
{
public Type type;
// when serializing, store as a string
[DataMember]
string TypeString
{
get
{
if (type == null)
return null;
return type.FullName;
}
set
{
if (value == null)
type = null;
else
{
type = Type.GetType(value);
}
}
}
// constructors
public SerializableType()
{
type = null;
}
public SerializableType(Type t)
{
type = t;
}
// allow SerializableType to implicitly be converted to and from System.Type
static public implicit operator Type(SerializableType stype)
{
return stype.type;
}
static public implicit operator SerializableType(Type t)
{
return new SerializableType(t);
}
// overload the == and != operators
public static bool operator ==(SerializableType a, SerializableType b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
// Return true if the fields match:
return a.type == b.type;
}
public static bool operator !=(SerializableType a, SerializableType b)
{
return !(a == b);
}
// we don't need to overload operators between SerializableType and System.Type because we already enabled them to implicitly convert
public override int GetHashCode()
{
return type.GetHashCode();
}
// overload the .Equals method
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to SerializableType return false.
SerializableType p = obj as SerializableType;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (type == p.type);
}
public bool Equals(SerializableType p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (type == p.type);
}
}
e um exemplo de uso:
[DataContract]
public class A
{
...
[DataMember]
private Dictionary<SerializableType, B> _bees;
...
public B GetB(Type type)
{
return _bees[type];
}
...
}
Você também pode considerar usar AssemblyQualifiedName em vez de Type.FullName - veja o comentário de @GreyCloud
Brian resposta funciona bem se o tipo estiver no mesmo assembly que a chamada (como GreyCloud apontou em um dos comentários).Então se o tipo estiver em outro assembly você precisa usar o AssemblyQualifiedName como GreyCloud também apontou.
Contudo como o AssemblyQualifiedName salva a versão, se seus assemblies tiverem uma versão diferente daquela na string onde você tem o tipo, não funcionará.
No meu caso, isso foi um problema e resolvi assim:
string typeName = typeof (MyClass).FullName;
Type type = GetTypeFrom(typeName);
object myInstance = Activator.CreateInstance(type);
Método GetTypeFrom
private Type GetTypeFrom(string valueType)
{
var type = Type.GetType(valueType);
if (type != null)
return type;
try
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
//To speed things up, we check first in the already loaded assemblies.
foreach (var assembly in assemblies)
{
type = assembly.GetType(valueType);
if (type != null)
break;
}
if (type != null)
return type;
var loadedAssemblies = assemblies.ToList();
foreach (var loadedAssembly in assemblies)
{
foreach (AssemblyName referencedAssemblyName in loadedAssembly.GetReferencedAssemblies())
{
var found = loadedAssemblies.All(x => x.GetName() != referencedAssemblyName);
if (!found)
{
try
{
var referencedAssembly = Assembly.Load(referencedAssemblyName);
type = referencedAssembly.GetType(valueType);
if (type != null)
break;
loadedAssemblies.Add(referencedAssembly);
}
catch
{
//We will ignore this, because the Type might still be in one of the other Assemblies.
}
}
}
}
}
catch(Exception exception)
{
//throw my custom exception
}
if (type == null)
{
//throw my custom exception.
}
return type;
}
Estou postando isso caso alguém precise.
De acordo com a documentação do MSDN de System.Type [1], você deve ser capaz de serializar o objeto System.Type.No entanto, como o erro se refere explicitamente a System.Text.StringBuilder, essa é provavelmente a classe que está causando o erro de serialização.
[1] Tipo Classe (Sistema) - http://msdn.microsoft.com/en-us/library/system.type.aspx
Acabei de olhar sua definição, ela não está marcada como Serializable.Se você realmente precisa que esses dados sejam serializados, talvez seja necessário convertê-los em uma classe personalizada marcada como tal.
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)]
Me deparei com esse problema ao tentar fazer a serialização binária no padrão .net 2.0.Acabei resolvendo o problema usando um custom SurrogateSelector
e SerializationBinder
.
O TypeSerializationBinder
foi necessário porque a estrutura estava tendo problemas para resolver System.RuntimeType
antes de chegar SurrogateSelector
.Eu realmente não entendo por que o tipo deve ser resolvido antes desta etapa ...
Aqui está o código:
// Serializes and deserializes System.Type
public class TypeSerializationSurrogate : ISerializationSurrogate {
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) {
info.AddValue(nameof(Type.FullName), (obj as Type).FullName);
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) {
return Type.GetType(info.GetString(nameof(Type.FullName)));
}
}
// Just a stub, doesn't need an implementation
public class TypeStub : Type { ... }
// Binds "System.RuntimeType" to our TypeStub
public class TypeSerializationBinder : SerializationBinder {
public override Type BindToType(string assemblyName, string typeName) {
if(typeName == "System.RuntimeType") {
return typeof(TypeStub);
}
return Type.GetType($"{typeName}, {assemblyName}");
}
}
// Selected out TypeSerializationSurrogate when [de]serializing Type
public class TypeSurrogateSelector : ISurrogateSelector {
public virtual void ChainSelector(ISurrogateSelector selector) => throw new NotSupportedException();
public virtual ISurrogateSelector GetNextSelector() => throw new NotSupportedException();
public virtual ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector) {
if(typeof(Type).IsAssignableFrom(type)) {
selector = this;
return new TypeSerializationSurrogate();
}
selector = null;
return null;
}
}
Exemplo de uso:
byte[] bytes
var serializeFormatter = new BinaryFormatter() {
SurrogateSelector = new TypeSurrogateSelector()
}
using (var stream = new MemoryStream()) {
serializeFormatter.Serialize(stream, typeof(string));
bytes = stream.ToArray();
}
var deserializeFormatter = new BinaryFormatter() {
SurrogateSelector = new TypeSurrogateSelector(),
Binder = new TypeDeserializationBinder()
}
using (var stream = new MemoryStream(bytes)) {
type = (Type)deserializeFormatter .Deserialize(stream);
Assert.Equal(typeof(string), type);
}