C# 为什么 .NET 允许将 SerializableAttribute 应用于枚举?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9196529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:19:44  来源:igfitidea点击:

Why does .NET allow the SerializableAttribute to be applied to enumerations?

c#serializationenums

提问by cellik

I have a class and one property is enum. Something like this:

我有一个类,一个属性是枚举。像这样的东西:

    //Do i need [Serializable]    
    public enum SexEnum
    {
         Male,
         Female
    }

    [Serializable]
    public class Person
    {
         string Name {get;set;}
         SexEnum Sex {get;set;} 
    }

When I serialize Personwith BinaryFormatter, do I need [Serializable]at the enum decleration? It works fine without it but then why does it allow the [Serializable]attribute in the enum decleration?

当我用 序列化PersonBinaryFormatter,我需要[Serializable]在枚举声明中吗?没有它它可以正常工作,但是为什么它允许[Serializable]枚举声明中的属性?

采纳答案by Tom Carter

.NET knows how to automatically serialize all the simple built in types so that's why you don't need to specify it.

.NET 知道如何自动序列化所有简单的内置类型,因此您无需指定它。

I think if .NET dissallowed the serializable attribute for items that are serializable it would be more confusing. The fact that you can decide to add it or leave it out is a matter of taste.

我认为如果 .NET 不允许可序列化项目的可序列化属性,那会更令人困惑。您可以决定添加或删除它的事实是一个品味问题。