在类上实现时,我不了解该[NonSerialized]
属性的使用ISerializable
。我参加了“C# 编程”(Microsoft 20-483)课程,它在几个示例中使用,但没有详细说明。
上这堂课:
[Serializable]
public class TestNonSerializable : ISerializable
{
public string FirstName { get; set; }
public string LastName { get; set; }
[NonSerialized]
private int _Age;
public int Age
{
get { return this._Age; }
set { this._Age = value; }
}
public TestNonSerializable()
{ }
public TestNonSerializable(SerializationInfo info, StreamingContext context)
{
FirstName = info.GetValue("Name", typeof(string)) as string;
LastName = info.GetValue("LastName", typeof(string)) as string;
// I expect this to throw an exception because the value doesn't exists.
// But it exists!
Age = (int)info.GetValue("Age", typeof(int));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", FirstName);
info.AddValue("LastName", LastName);
// I expect this to be empty
info.AddValue("Age", Age);
}
}
我评论了我的期望:_Age
是一个我不想序列化的私有字段。我专门写了GetObjectData
序列化它。这是一件很奇怪的事情,但我想了解如何[NonSerialized]
处理。
如果我在Main
:
class Program
{
static void Main(string[] args)
{
var myObject = new TestNonSerializable()
{
FirstName = "Foo",
LastName = "Bar",
Age = 32,
};
// Instanciate a SOAP formatter
IFormatter soapFormat = new SoapFormatter();
// Serialize to a file
using (FileStream buffer = File.Create(@"D:\temp\TestNonSerializable.txt"))
{
// In the file generated, I expect the age to be empty. But the value
// is set to 32
soapFormat.Serialize(buffer, myObject);
}
// Deserialize from a file
using (FileStream buffer = File.OpenRead(@"D:\temp\TestNonSerializable.txt"))
{
// The age is being deserialized
var hydratedObject = soapFormat.Deserialize(buffer);
}
}
}
年龄在那里......在序列化对象所在的文件和再水化对象中。我的问题是:为什么?在这种情况下,属性有什么用,因为[NonSerialized]
我们只需要不添加方法?我显然错过了一些东西,但我不知道是什么。谢谢!Age
GetObjectData
编辑:课程中的示例:
[Serializable]
public class ServiceConfiguration : ISerializable
{
[NonSerialized]
private Guid _internalId;
public string ConfigName { get; set; }
public string DatabaseHostName { get; set; }
public string ApplicationDataPath { get; set; }
public ServiceConfiguration()
{
}
public ServiceConfiguration(SerializationInfo info, StreamingContext ctxt)
{
this.ConfigName
= info.GetValue("ConfigName", typeof(string)).ToString();
this.DatabaseHostName
= info.GetValue("DatabaseHostName", typeof(string)).ToString();
this.ApplicationDataPath
= info.GetValue("ApplicationDataPath", typeof(string)).ToString();
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ConfigName", this.ConfigName);
info.AddValue("DatabaseHostName", this.DatabaseHostName);
info.AddValue("ApplicationDataPath", this.ApplicationDataPath);
}
}