不使用[Serializable]时[NonSerialized]的好处

Tim*_* W. 11 c# serialization nonserializedattribute

我正在查看我正在处理的项目中的一些现有代码,我找到了一个实现为:

public class ThingOne
{
    private int A;

    private int B;

    [NonSerialized]
    private System.Timers.Timer timer1;
}
Run Code Online (Sandbox Code Playgroud)

它不应该看起来更像这样吗?

[Serializable]
public class ThingOne
{
    private int A;

    private int B;

    [NonSerialized]
    private System.Timers.Timer timer1;
}
Run Code Online (Sandbox Code Playgroud)

或者,即使类本身不是Serializable,添加[NonSerialized]还有一些额外的好处吗?

kem*_*002 14

或者,即使类本身不是Serializable,添加[NonSerialized]还有一些额外的好处吗?

该类未密封,因此另一个类可以从该对象继承.该类可以标记为Serializable,然后NotSerializable属性将起作用.(虽然没有指出私人会员).

请记住,您也可以通过反射检查属性.运行时可能不会使用它来检查应该和不应该序列化的内容,它可以用作程序中其他东西的标记来处理某种自定义序列化(我不是说这是个好主意)至少).


Gre*_*reg 8

未使用Serializable时,NonSerialized将不起作用.默认情况下,类及其成员是不可序列化的.

当类未被序列化时声明NonSerialized的唯一优点是在类被Serialized对象继承的情况下,然后继承的成员将是不可序列化的.

来自MSDN:

'NonSerialized'属性不会影响此成员,因为其包含的类不会公开为'Serializable'.

默认情况下,类及其成员是不可序列化的.仅当序列化类的成员不应序列化时,才需要NonSerializedAttribute属性.


Jon*_*nna 5

I can think of two reasons:

  1. It could be vital that the field isn't serialised. Hence if in the future the class is made serialisable, this won't introduce a bug, inefficiency or security issue, because without it marking the class serialisable will also do so for the field.

  2. They could be doing some sort of custom use of the attribute

In case 2 it'll be clear from elsewhere in the code that this is what's happening. Number 1 is good practice though.

Case 1 is good practice, it can be worth balancing YAGNI ("You Aren't Gonna Need It" - not doing work "in case it's needed later") with considering "okay, but if I do need it later, it'll be a disaster if someone misses that this field is an exception.

So, while it has no effect here, it is definitely a good practice for scenarios where it begins to have an effect.

Edit: Another possibility is that it is cruft from a previous version where it was indeed serialisable or the author was in two minds at the time and it was never entirely "finished" (is working code ever entirely finished?). Just because something is in code, doesn't mean it was meant to be that way. Still, if it's really important that something not be serialised, I still say it's good practice to mark this for the reason given above.