What is an example of “this” assignment in C#?

前端 未结 6 2298
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 01:46

Does anybody have useful example of this assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer

6条回答
  •  暖寄归人
    2020-12-11 02:12

    I know this question has long been answered and discussion has stopped, but here's a case I didn't see mentioned anywhere on the interwebs and thought it may be useful to share here.

    I've used this to maintain immutability of members while still supporting serialization. Consider a struct defined like this:

    public struct SampleStruct : IXmlSerializable
    {
        private readonly int _data;
    
        public int Data { get { return _data; } }
    
        public SampleStruct(int data)
        {
             _data = data;
        }
    
        #region IXmlSerializableMembers
    
        public XmlSchema GetSchema() { return null; }
    
        public void ReadXml(XmlReader reader)
        {
            this = new SampleStruct(int.Parse(reader.ReadString()));
        }
    
        public void WriteXml(XmlWriter writer
        {
            writer.WriteString(data.ToString());
        }
    
        #endregion
    }
    

    Since we're allowed to overwrite this, we can maintain the immutability of _data held within a single instance. This has the added benefit of when deserializing new values you're guaranteed a fresh instance, which is sometimes a nice guarantee! }

提交回复
热议问题