Enforcing serializable from an interface without forcing classes to custom serialize in C#

后端 未结 5 1141
梦毁少年i
梦毁少年i 2021-02-19 23:00

I have an interface that defines some methods I would like certain classes to implement.

public interface IMyInterface
{
    MethodA;
    MethodB;
}

Additi

相关标签:
5条回答
  • 2021-02-19 23:42

    There does not seem to be a way to do this, but I wish there were.

    Note two things though:

    • The Serializable attribute can not be inherited from a base class, even if the base class is marked as abstract.

    • You don't technically need the Serializable attribute, IF you are using an XmlSerializer because it does not make use of object graphs.

    0 讨论(0)
  • 2021-02-19 23:42

    If you want to use the default serialization then you need to add the SerializableAttribute . One alternative would be to use an abstract class instead of an interface, then add the SerializableAttribute to the abstract class. If you're implementing your own custom serialization then you want to implement ISerializable, otherwise stick with SerializableAttribute .

    0 讨论(0)
  • 2021-02-19 23:45

    Write a class that implements ISerializationSurrogate and use that to serialize classes that aren't serializable or where you're not sure of the serialization implementation.

    0 讨论(0)
  • 2021-02-19 23:51

    You could write a custom FxCop rule and validate check-ins against it.

    0 讨论(0)
  • 2021-02-19 23:54

    Thanks for the replies. It would be nice to be able to force classes derived from an interface to implement serialization without this then forcing them to custom serialize but it doesn't seem to be possible.

    0 讨论(0)
提交回复
热议问题