System.Exception.Data Property

前端 未结 3 1579
Happy的楠姐
Happy的楠姐 2021-02-05 01:54

The System.Exception class (actually any exception) has Data property which is almost always empty. While throwing exceptions, should this field be of any use? Or does it have s

3条回答
  •  离开以前
    2021-02-05 02:27

    Another note here, what I do when I inherit an exception and add properties, is to make the properties actually get and set from the data dictionary, and not from local variables.

    [Serializable]
    public class PacketParseException : Exception
    {
        public byte[] ByteData
        {
            get
            {
                return (byte[])this.Data["ByteData"];
            }
        }
    
        public PacketParseException(string message, byte[] data, Exception inner) : base(message, inner)
        {
            this.Data.Add("ByteData", data);
        }
    }
    

    The way I see it, then the internal data is available from an Exception as well, for example when logging, so no need to cast to actual type.

提交回复
热议问题