[英]Error during class serialization: type is not marked serializable
I have a class marked as [Serializable]. 我有一个标记为[可序列化]的课程。 It has a property tha I don't wan to serialize. 它具有我不想序列化的属性。 But at runtime I got an error during serialization. 但是在运行时,我在序列化过程中出错。 These are my classes: 这些是我的课程:
public interface IMyNonSerializable
{
...
}
public class MyNonSerializable : IMyNonSerializable
{
...
}
[Serializable]
public class MySerializable
{
public string MyProp1{get;set;}
[NonSerialized]
public string MyProp2{get;set;}
public IMyNonSerializable MyNonSerializableProp{get;set;}
}
Here the code I use to serialize my MySerializable class: 这是我用来序列化MySerializable类的代码:
Stream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Context = new StreamingContext(StreamingContextStates.Clone);
formatter.Serialize(stream, obj);
At runtime I got this error: 在运行时我收到此错误:
> System.Runtime.Serialization.SerializationException
HResult=0x8013150C
Message=Type 'MyNonSerializable' is not marked as serializable.
Source=mscorlib
Is there a way to serialize my class avoiding to serialize my non-serializable class without implement ISerializable interface? 有没有一种方法可以序列化我的类,从而避免在没有实现ISerializable接口的情况下序列化我的不可序列化的类?
Create backing field and apply the [NonSerialized]
attribute to this one: 创建支持字段并将[NonSerialized]
属性应用于此字段:
[Serializable]
public class MySerializable
{
public string MyProp1 { get; set; }
public string MyProp2 { get; set; }
[NonSerialized]
private IMyNonSerializable _myNonSerializableProp;
public IMyNonSerializable MyNonSerializableProp
{
get { return _myNonSerializableProp; }
set { _myNonSerializableProp = value; }
}
}
If you are using C# 7.3 or later, you could use a field-targeted attribute on the auto-generated property without creating a backing field: 如果使用的是C#7.3或更高版本,则可以在自动生成的属性上使用以字段定位的属性,而无需创建后备字段:
[field: NonSerialized]
public IMyNonSerializable MyNonSerializableProp { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.