程序集 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' 中的类型 'System.Data.DataRow' 未标记为可序列化

Type 'System.Data.DataRow' in Assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable

我在将对象序列化为流时遇到以下错误。

Type 'System.Data.DataRow' in Assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable

internal static object CloneObject(object obj)
{
    MemoryStream ms = null;
    object objClone = null;

    try
    {
        // Create a memory stream and a formatter.
        ms = new MemoryStream();
        BinaryFormatter bf= new BinaryFormatter();

        // Serialize the object into the stream.
        bf.Serialize(ms, obj);
        // Position stream pointer back to first byte.
        ms.Seek(0, SeekOrigin.Begin);
        // De serialize into another object.
        objClone = bf.Deserialize(ms);
    }
    finally
    {
        // Release memory.
        if (ms != null)
            ms.Close();
    }
    return objClone;
}

通过读取异常,对象中好像有一个dataRow没有被序列化。

如何识别在我的代码中导致此问题的 dataRow

首先,您需要找到调用此代码的位置。

在 Visual Studio 中,您可以右键单击函数名称并单击 "Find All References" - 这应该会给您一个开始(参见 documentation on finding objects, definitions and references

另一种选择是在调试时使用 CallStack 来找出调用的来源。

如果您正在尝试克隆 DataTableDataTable.Clone 方法可能就是您想要的。

如果你想序列化一个class的实例,class必须被标记为[Serializable]。 DataRow 未标记,因此您无法序列化 DataRow 类型的对象。

找到了这个问题的根本原因...在 class 文件之一中声明了一个全局数据行变量。 class 被标记为序列化。

删除该数据行后,问题已解决。

谢谢,

-湿婆