好的,这个问题已经在 SO 中得到了回答,这里是如何将值传递给基础构造函数
public SMAPIException( string message) : base(message)
{
TranslationHelper instance = TranslationHelper.GetTranslationHelper; // singleton class
string localizedErrMessage = instance.GetTranslatedMessage(message, "" );
// code removed for brevity sake.
}
Run Code Online (Sandbox Code Playgroud)
但是假设我想操作“消息”信息,然后设置基类构造函数,然后怎么做。
伪代码如下:
public SMAPIException( string message) : base(localizedErrMessage)
{
TranslationHelper instance = TranslationHelper.GetTranslationHelper; // singleton class
string localizedErrMessage = instance.GetTranslatedMessage(message, "" );
// code removed for brevity sake.
}
Run Code Online (Sandbox Code Playgroud)
// 所以基本上我希望将 localizedErrMessage 而不是消息发送到基类构造函数,这可能吗?请指导我。
这应该有效:
public class SMAPIException : Exception
{
public SMAPIException(string str) : base(ChangeString(str))
{
/* Since SMAPIException derives from Exceptions we can use
* all public properties of Exception
*/
Console.WriteLine(base.Message);
}
private static string ChangeString(string message)
{
return $"Exception is: \"{message}\"";
}
}
Run Code Online (Sandbox Code Playgroud)
需要注意的是ChangeString必须static!
例子:
SMAPIException ex = new SMAPIException("Here comes a new SMAPIException");
// OUTPUT //
// Exception is "Here comes a new SMAPIException"
Run Code Online (Sandbox Code Playgroud)
检查您的BaseType:
// Summary:
// Initializes a new instance of the System.Exception class with a specified error
// message.
//
// Parameters:
// message:
// The message that describes the error.
public Exception(string message);
Run Code Online (Sandbox Code Playgroud)
调用base(string message)是一样的new Exception("message")
因此,您可以使用Message-Property获取传递的值。
但 !这仅在SMAPIException不隐藏其基本成员时才有效new string Message {get; set;} !