我需要编写一个根据输入参数自动确定消息的异常类。我怎样才能将该动态消息传递给 base()?
这是我想做的代码,但它不起作用
public class MyException : Exception
{
public MyException(int ErrCode, Dictionary<string, string> Params) : base(msg_external)
{
ErrorDetail = ErrorList[ErrCode];
string msg_internal = "";
string msg_external = "";
foreach (var item in Params)
{
msg_internal = ErrorDetail.MessageInternal.Replace(item.Key, item.Value);
msg_external = ErrorDetail.MessageExternal.Replace(item.Key, item.Value);
}
//now I need to pass msg_external to the base(). how?
}
}
这个问题不是关于在我的构造函数之后调用构造函数,而是关于将不同的值传递给父构造函数。
最佳答案
这里的代码将执行您想要的操作。
假设输入良好。建议进行错误检查。
public class MyException : Exception
{
private static string BaseExceptionMessage(int ErrCode, Dictionary<string,string> Params)
{
return Params.Aggregate(ErrorList[ErrCode].MessageExternal, (i, a) => i.Replace(a.Key, a.Value));
}
public MyException(int ErrCode, Dictionary<string, string> Params) : base(BaseExceptionMessage(ErrCode, Params))
{
ErrorDetail = ErrorList[ErrCode];
string msg_internal = "";
string msg_external = "";
foreach (var item in Params)
{
msg_internal = ErrorDetail.MessageInternal.Replace(item.Key, item.Value);
msg_external = ErrorDetail.MessageExternal.Replace(item.Key, item.Value);
}
}
}
关于c# 使用参数的计算结果调用 base(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45286807/