简体   繁体   English

C#强制子类实现Serializable

[英]C# force subclass to implement Serializable

I have an interface IStorageManager that allows me to store data, different implementations are for json-file-based storage, xml-file-based, etc 我有一个接口IStorageManager ,允许我存储数据,不同的实现是基于json文件的存储,基于xml文件,等等

I have the interface IStorable and I want to force all classes implementing IStorable to have the [Serializable] header. 我有接口IStorable ,我想强制所有实现IStorable类具有[Serializable]标头。 So in the IStorageManager I can implement it like this : 所以在IStorageManager我可以像这样实现它:

public interface IStorageManager
{
    IStorable Load<IStorable>(string Path);
    void Save<IStorable>(IStorable objToSave, string path);
}
public class XMLStorageManager : IStorageManager
{
    public void Save<T>(T objToSave, string path)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
        using (TextWriter writer = new System.IO.StreamWriter(System.IO.Path.GetFullPath(path)))
        {
            serializer.Serialize(writer, typeof(T));
        }
    }
}

Is there a way to specify that in the interface ?? 有没有办法在界面中指定?

The short answer is No you can't enforce an Attribute through an interface. 简短的回答是“不,您不能通过接口强制执行属性”。 In principle, interfaces are about contracts (behaviour) while serialisation is about state which is not normally reflected in interfaces. 原则上,接口是关于契约(行为)的,而序列化是关于通常不在接口中反映的状态。

The options you have are: 你有的选择是:

  • Instead of using an interface for "storable" objects use an abstract class (like StorableBase ) that consumer code should inherit from. 不使用“可存储”对象的接口,而是使用消费者代码应该继承的抽象类(如StorableBase )。 Main drawback of this is that it restricts the types of classes the consumer code can use with your library. 这样做的主要缺点是它限制了消费者代码可以与库一起使用的类的类型。 Also note that not all serialization libraries check all the class hierarchy when looking for Serializable attribute and some might check only the concrete class. 另请注意,在查找Serializable属性时,并非所有序列化库都会检查所有类层次结构,有些可能只检查具体类。 You can on top of that implement the ISerializable interface on that abstract class to have more control over the serialisation process. 您可以在该抽象类上实现ISerializable接口,以便更好地控制序列化过程。 See here for details. 详情请见此处。

  • Roslyn introduced the concept of Code Analyzers. Roslyn介绍了代码分析器的概念。 You can create a custom code analyzer that checks at compile time for your rule. 您可以创建一个自定义代码分析器,在编译时检查您的规则。 See here for more details and an example . 有关详细信息和示例,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM