Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

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

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 Person with 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?

question from:https://stackoverflow.com/questions/9196529/why-does-net-allow-the-serializableattribute-to-be-applied-to-enumerations

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...