如何在C#中定义自己的消息?

Jim*_*eth 10 .net c# exception

我想定义一个具有两个特殊属性的自定义异常:Field和FieldValue,我希望从异常构造函数中的这两个值构建消息.不幸的是,消息是只读的.

这就是我所拥有的,但它仍然需要传递消息.

    public class FieldFormatException: FormatException
    {
        private Fields _field;
        private string _fieldValue;
        public Fields Field{ get{ return _field; } }
        public string FieldValue { get { return _value; } }
        public FieldFormatException() : base() { }
        private FieldFormatException(string message) { }
        public FieldFormatException(string message, Fields field, string value): 
            base(message)
        {
            _fieldValue = value;
            _field = field;               
        }
        public FieldFormatException(string message, Exception inner, Fields field, string value): 
            base(message, inner)
        {
            _fieldValue = value;
            _field = field;
        }
        protected FieldFormatException(System.Runtime.Serialization.SerializationInfo info,
              System.Runtime.Serialization.StreamingContext context): base(info, context){}
    }
Run Code Online (Sandbox Code Playgroud)

如何从构造函数中删除Message作为参数,然后根据Field和FieldValue的值设置消息?

Ste*_*ger 25

不确定我是否理解你的问题,但是这个呢?

    public FieldFormatException(Fields field, string value): 
        base(BuildMessage(field, value))
    {
    }

    private static string BuildMessage(Fields field, string value)
    {
       // return the message you want
    }
Run Code Online (Sandbox Code Playgroud)


Mar*_*ers 18

覆盖它:

    public override string Message
    {
        get
        {
            return string.Format("My message: {0}, {1}", Field, FieldValue);
        }
    }
Run Code Online (Sandbox Code Playgroud)

正如评论中所讨论的那样,即使您说您不想在构造函数中使用消息,您也可以考虑允许用户有选择地将自己的消息传递给异常的构造函数并显示它.

  • 你不应该这样做,因为它是一个标准的设计指南,有一个异常的创建者可以定义的消息属性(FxCop会抱怨afaik).请考虑重写ToString,或者提供一个将默认值应用于Message属性的其他构造函数. (2认同)