为什么异常消息属性只读?

ROB*_*SON 4 c# exception

也许C#中最神秘的事情是Exception类的message属性是只读的.可能是因为我不明白这个的原因,当我尝试创建从Exception派生的合理异常类时,我感到很沮丧.

例如(实际上我正在尝试做的事情),我想在尝试连接OPC服务器时创建异常.如果尝试失败,则会引发OPCException类型的对象,但我想向用户提供更多信息.所以,我有一个名为OPCCaException的类,它接受三个参数:原始异常的返回代码,服务器名称和主机名.

public class OPCCaException : Exception
{
    public OPCCaException(ReturnCode returnCode, string serverName, string nodeName)
    {
        if (nodeName == "")
        {
            this.Message = "Failed to connect to OPC server "+ serverName + 
                           ": " + TranslateReturnCode()";
        }
        else
        {
            this.Message = "Failed to connect to OPC server "+ serverName + 
                           " on node " + nodeName +
                           ": " + TranslateReturnCode()";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在我看来,这是一个非常合理的事情,但它不会编译,因为Message属性是只读的.设置消息的唯一方法是将其传递给基类构造函数.为什么我不能在派生类的构造函数中设置它?我能想到对参数进行任何处理的唯一方法是创建一个静态类来构建消息:

public class OPCCaException : Exception
{
    private static string BuildMessage(<some arguments>)
    {
        string message = "some message";
        return message;
    }
    public OPCCaException(ReturnCode returnCode, string serverName, string nodeName) :
        base(BuildMessage(returnCode, serverName, nodeName))
    {
    }
 }
Run Code Online (Sandbox Code Playgroud)

我不知道是否会编译.

这样做的标准方法是什么?

Ale*_*kov 9

public virtual string Message

消息是虚拟的 - 因此您可以在课堂上轻松覆盖它.

public class OPCCaException : Exception
{...
  public override string Message 
  {
    get { return "My fancy text";}
  }
}
Run Code Online (Sandbox Code Playgroud)

另外更标准的方法是通过调用将消息传递给基类构造函数:

public OPCCaException(...) : base(buildMessage(...))
{
}
Run Code Online (Sandbox Code Playgroud)