using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
namespace HslCommunication.BasicFramework
{
/****************************************************************************
*
* 创建日期: 2017年6月25日 15:45:40
* 功能: 一个基础的泛型异常类
* 参考: 参考《CLR Via C#》P413
*
***************************************************************************/
///
/// 一个自定义的支持序列化反序列化的异常类,具体用法参照第四版《CLR Via C#》P414
///
/// 泛型异常
[Serializable]
public sealed class Exception : Exception, ISerializable where TExceptionArgs : ExceptionArgs
{
///
/// 用于反序列化的
///
private const string c_args = "Args";
private readonly TExceptionArgs m_args;
///
/// 消息
///
public TExceptionArgs Args { get { return m_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)
{
m_args = args;
}
/******************************************************************************************************
*
* 这个构造器用于反序列化的,由于类是密封的,所以构造器是私有的
* 如果这个构造器不是密封的,这个构造器就应该是受保护的
*
******************************************************************************************************/
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
private Exception(SerializationInfo info, StreamingContext context) : base(info, context)
{
m_args = (TExceptionArgs)info.GetValue(c_args, typeof(TExceptionArgs));
}
/******************************************************************************************************
*
* 这个方法用于序列化,由于ISerializable接口的存在,这个方法必须是公开的
*
******************************************************************************************************/
///
/// 获取存储对象的序列化数据
///
/// 序列化的信息
/// 流的上下文
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(c_args, m_args);
base.GetObjectData(info, context);
}
///
/// 获取描述当前异常的消息
///
public override string Message
{
get
{
string baseMsg = base.Message;
return m_args == null ? baseMsg : baseMsg + " (" + m_args.Message + ")";
}
}
///
/// 确定指定的object是否等于当前的object
///
/// 异常对象
/// 是否一致
public override bool Equals(object obj)
{
Exception other = obj as Exception;
if (other == null) return false;
return object.Equals(m_args, other.m_args) && base.Equals(obj);
}
///
/// 用作特定类型的哈希函数
///
/// int值
public override int GetHashCode()
{
return base.GetHashCode();
}
}
///
/// 异常消息基类
///
[Serializable]
public abstract class ExceptionArgs
{
///
/// 获取消息文本
///
public virtual string Message
{
get { return string.Empty; }
}
}
}