Skip to main content
 首页 » 编程设计

c#之我如何概括这种反序列化方法

2024年02月06日14think

如何概括以下反序列化方法?

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

如何进行动态转换?非常感谢任何帮助。

请您参考如下方法:

您不能在 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; 
}