Jeffery Richter’s Exception<TExceptionArgs>

using System;
using System.Runtime.Serialization;
using System.Security.Permissions;

namespace GenericException
{
    [Serializable]
    public sealed class Exception<TExceptionArgs> : Exception, ISerializable
        where TExceptionArgs : ExceptionArgs
    {
        private const String CArgs = "Args";
        private readonly TExceptionArgs _args;

        public TExceptionArgs Args { get { return _args; } }


        public Exception(String message = null, Exception innerException = null)
            : this(null, message, innerException) { }

        public Exception(TExceptionArgs args, String message = null, Exception innerException = null)
            : base(message, innerException)
        {
            _args = args;
        }


        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        private Exception(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            _args = (TExceptionArgs)info.GetValue(CArgs, typeof(TExceptionArgs));
        }

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue(CArgs, _args);
            base.GetObjectData(info, context);
        }

        public override string Message
        {
            get
            {
                String baseMessage = base.Message;
                return _args == null ? baseMessage : baseMessage + "(" + _args.Message + ")";
            }
        }

        public override bool Equals(object obj)
        {
            Exception<TExceptionArgs> other = obj as Exception<TExceptionArgs>;
            if (other==null)
            {
                return false;
            }

            return Object.Equals(_args, other.Args) && base.Equals(obj);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }

    [Serializable]
    public abstract class ExceptionArgs
    {
        public virtual String Message { get { return String.Empty; } }
    }
}
posted @ 2012-08-22 23:24  HelloWorld.Michael  阅读(228)  评论(0编辑  收藏  举报