Set default value in a DataContract?

后端 未结 2 1110
一向
一向 2020-12-30 01:58

How can I set a default value to a DataMember for example for the one shown below:

I want to set ScanDevice=\"XeroxScan\" by default

    [DataMember]         


        
相关标签:
2条回答
  • 2020-12-30 02:32

    I've usually done this with a pattern like this:

    [DataContract]
    public class MyClass
    {
        [DataMember]
        public string ScanDevice { get; set; }
    
        public MyClass()
        {
            SetDefaults();
        }
    
        [OnDeserializing]
        private void OnDeserializing(StreamingContext context)
        {
            SetDefaults();
        }
    
        private void SetDefaults()
        {
            ScanDevice = "XeroxScan";
        }
    }
    

    Don't forget the OnDeserializing, as your constructor will not be called during deserialization.

    0 讨论(0)
  • 2020-12-30 02:42

    If you want it always to default to XeroxScan, why not do something simple like:

    [DataMember(EmitDefaultValue = false)]
    public string ScanDevice= "XeroxScan";
    
    0 讨论(0)
提交回复
热议问题