如何推广这种反序列化方法?

时间:2014-12-10 19:47:49

标签: c#

如何推广以下反序列化方法?

public static bool DeSerializeAnyObject(ref Object MyObj, string fileName)
{

    if (string.IsNullOrEmpty(fileName)) { return false; }

    FileStream fs = new FileStream(fileName, FileMode.Open);
    BinaryFormatter formatter = new BinaryFormatter();
    try
    {
        MyObj = (MyObj.GetType()) formatter.Deserialize(fs);
    }
    catch (Exception ex)
    {
        Trace.WriteLine("Can't De-Serialise" + ex.ToString());
    }
    finally
    {
        fs.Close();
    }

   return true; 
}

我试图这样做,但不能通过这样做进行演员。

(MyObj.GetType())

如何制作动态广告?非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

你无法在C#中进行动态转换。

但是,由于您只是分配给一个对象,所以根本不需要进行投射!只需写下:

MyObj = formatter.Deserialize(fs);

请注意,由于MyObj未通过引用传递,因此该分配实际不会对调用者执行任何有用的操作。如果你问我,这也是一件非常奇怪的事情。

至少返回MyObj而不是返回无用的始终为真bool

你也可以这样做:

public static T DeserializeObject<T>(string fileName)
{
    T retValue = default(T);
    if (string.IsNullOrEmpty(fileName)) 
        return retValue;

    FileStream fs = new FileStream(fileName, FileMode.Open);
    BinaryFormatter formatter = new BinaryFormatter();
    try
    {
        retValue = (T)formatter.Deserialize(fs);
    }
    catch (Exception ex)
    {
        Trace.WriteLine("Can't De-Serialise" + ex.ToString());
    }
    finally
    {
        fs.Close();
    }

    return retValue;
}

答案 1 :(得分:1)

这是一个非常有趣的选择,但对于动态转换,您可以执行Convert.ChangeType()http://msdn.microsoft.com/en-us/library/dtb69x08(v=vs.110).aspx),但您的反序列化对象也必须实现IConvertible接口。

这样的事情:

public static bool DeSerializeAnyObject(out Object MyObj, Type MyType, string fileName)
{

    if (string.IsNullOrEmpty(fileName)) { MyObj = null; return false; }

    FileStream fs = new FileStream(fileName, FileMode.Open);
    BinaryFormatter formatter = new BinaryFormatter();
    try
    {
        MyObj = Convert.ChangeType(MyTypeformatter.Deserialize(fs), MyType);
    }
    catch (Exception ex)
    {
        Trace.WriteLine("Can't De-Serialise or Convert: " + ex.ToString());
        MyObj = null;
        return false;
    }
    finally
    {
        fs.Close();
    }

   return true; 
}

编辑:在进一步的细节之后,您可能想要创建一个额外的方法来解决我目前使用的方法:

if (DeSerializeAnyObject(out obj, obj.GetType(), fileName)) {...}

以及与您的签名匹配的包装器方法:

public static bool DeSerializeAnyObject(ref Object MyObj, string fileName) {
    return DeSerializeAnyObject(out MyObj, MyObj.getType(), fileName);
}
相关问题