System.Exception.Data Property

前端 未结 3 1583
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:44

    With the new CallerMemberNameAttribute it's even easier to use the Data property for storage:

    public class BetterException : Exception
    {
        protected T GetValue([CallerMemberNameAttribute] string propertyName = "")
        {
            return (T)Data[propertyName];
        }
    
        protected void SetValue(T value, [CallerMemberNameAttribute] string propertyName = "")
        {
            Data[propertyName] = value;
        }
    }
    

    Usage:

    class MyException : BetterException
    {
        public MyException(string name)
        {
            Name = name;
        }
    
        public string Name
        {
            get { return GetValue(); }
            set { SetValue(value); }
        }
    }
    

提交回复
热议问题