在 C# 中使字段默认非序列化

make fields non-serialized by default in c#

是否可以在 c# 中使字段默认为非序列化,这在 .NET 2.0 中也适用?

Serializedclass中的大部分字段是非序列化的,只有少数字段需要序列化。

我知道一个属性可以应用于多个字段,但这不是我需要的。

将class序列化为XML.

[Serializable()]
class MyClass
{
  [NonSerialized]
  protected double field1;
}

根据您序列化类型的具体方式,您可以在 class 上使用 DataContract 属性。这允许您使用 DataMember 属性修饰要序列化的属性。

DataContractSerializer 结合使用时,序列化采用选择加入的方法,缺少属性的属性将不会被序列化。

using System.Runtime.Serialization;

[DataContract]
class MyClass
{      
    [DataMember]
    protected double field1; // This field is serialized

    protected double secretField; // This field is not        
}