【问题标题】:Deserialising using a string representation of the target type使用目标类型的字符串表示反序列化
【发布时间】:2013-10-11 02:37:40
【问题描述】:

我想反序列化为一个类型,但我只有那个类型的字符串表示。

我只知道该类型实现了ISomething

string typeName = "MyClass";

BinaryFormatter binaryFormatter = new BinaryFormatter();
byte[] data = Convert.FromBase64String(serialisedString);

using (MemoryStream memoryStream = new MemoryStream(data, 0, data.Length))
{
    return (ISomething)binaryFormatter.Deserialize(memoryStream) as ISomething;
}

但我在 BinaryFormatter.Deserialize 上得到以下异常:

无法将“System.RuntimeType”类型的对象转换为类型 'MyAssembly.ISomething'

如何转换为typeName 中存储的类名?

【问题讨论】:

  • 对象是如何序列化的?

标签: c# .net serialization casting type-conversion


【解决方案1】:

你可以使用:

Type type = Type.GetType(typeName);

要获取的类型的程序集限定名称。看 装配合格名称。如果类型在当前执行中 程序集或在 Mscorlib.dll 中,提供类型名称就足够了 由其命名空间限定。

Type.GetType()

您可以创建一个利用 XmlSerialiser 的通用反序列化方法:

public class XmlDeserialiser
{
    public T Deserialise<T>(string xml) where T : class
    {
        T foo;
        try
        {
            var serializer = new XmlSerializer(typeof(T));
            foo = (T)serializer.Deserialize(new XmlTextReader(new System.IO.StringReader(xml)));
        }
        catch(Exception ex)
        {
            Console.WriteLine("Failed to Deserialise " + xml + " " + ex);
            throw;
        }

        return foo;
    }
}

使用reflection拨打电话:

MethodInfo method = typeof(XmlDeserialiser).GetMethod("Deserialise"); // XmlDeserialiser is the class which contains your Deserialise method.
MethodInfo generic = method.MakeGenericMethod(type);
generic.Invoke(this, null);

【讨论】:

  • 我如何转换到type
【解决方案2】:

我认为最重要的是你想对结果做什么?

我的意思是,即使使用 Sam 的代码,您也会将结果放入一个对象类型的变量中。您不能为此使用 var 。因此,使用简单的反序列化或 Sam 的反序列化,您将获得相同的结果。

我的问题又是你想对结果做什么?

你想调用一些常用的方法吗? ISomething 是通用接口吗?

如果是这种情况,并且您事先知道,那么让您的所有类型都继承自 ISomething 之类的东西,然后将它们强制转换为它。如果不是,我无法想象你会对 tre 结果做什么。

我能想到的唯一用法(没有通用接口)是为每种类型使用案例,并为每个特定案例做不同的思考??? 但在那种情况下......你会知道序列化对象的类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多