好的,这个问题已在SO中得到解答,这里是How to pass value to base constructor
public SMAPIException( string message) : base(message)
{
TranslationHelper instance = TranslationHelper.GetTranslationHelper; // singleton class
string localizedErrMessage = instance.GetTranslatedMessage(message, "" );
// code removed for brevity sake.
}
但是假设我想操纵“消息”信息然后设置基类构造函数,然后如何操作它。
下面的伪代码:
public SMAPIException( string message) : base(localizedErrMessage)
{
TranslationHelper instance = TranslationHelper.GetTranslationHelper; // singleton class
string localizedErrMessage = instance.GetTranslatedMessage(message, "" );
// code removed for brevity sake.
}
//所以基本上我希望将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}\"";
}
}
请注意,ChangeString
必须是static
!
例:
SMAPIException ex = new SMAPIException("Here comes a new SMAPIException");
// OUTPUT //
// Exception is "Here comes a new SMAPIException"
检查你的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);
调用base(string message)
与new Exception("message")
相同
因此,您可以使用Message
-Property获取传递的值。
但是!这只有在SMAPIException
不隐藏它的基础成员new string Message {get; set;}
时才有效!
有一个静态工厂方法,并使构造函数私有:
class SMAPIException
{
private SMAPIException(string message) : base(message)
{
// whatever initialization
}
public static SMAPIException CreateNew(string message)
{
string localizedErrMessage;
// do whatever to set localizedErrMessage
return SMAPIException(localizedErrMessage);
}
}
然后你可以使用:
SMAPIException localizedEx = SMAPIException.CreateNew("unlocalizedString");
您可以在基类构造函数的参数列表中调用静态方法。
public SMAPIException( string message)
: base(TranslationHelper.GetTranslationHelper.GetTranslatedMessage(message, ""))
{
}