标题是有点抽象,所以也许更容易与一个具体的例子来解释:有没有办法在对基类构造函数的调用中使用可覆盖的行为?
我发现它有用有我的异常类需要一个枚举参数,而不是字符串消息。
throw new SpecificException(SpecificExceptionCode.ThisThingWentWrong);
这有几个原因,其中包括:
- 我可以encapulate所有的逻辑,在一个地方访问本地化的字符串资源
- 我可以很容易地确保我有字符串资源,使所有我的例外消息
- 检查单元测试中的正确异常消息更简单
我想写这种类型的异常的基类。派生异常类通常只是想提供自己的System.Resources.ResourceManager,但也可能提供额外的构造函数。麻烦来了,因为我只能在调用基类构造函数时调用静态方法。这使我是这样的:
public abstract class BaseException : ApplicationException
{
protected static ResourceManager m_resources;
public BaseException(System.Enum errorCode, params object[] messageArgs)
: base(ProcessError(errorCode, messageArgs))
{}
private static string ProcessError(Enum errorCode, params object[] messageArgs)
{
string errorMessage = m_resources.GetString(errorCode.ToString());
// Handling of messageArgs and trace logging
// ....
return finalError;
}
}
和
public class SpecificException : BaseException
{
static SpecificException()
{
m_resources = //.. Get an appropriate resource manager instance
}
public SpecificException(SpecificExceptionCode errorCode, params object[] messageArgs)
: base(errorCode, messageArgs)
{}
}
这工作,但我不满意它没有编译时暗示,派生类必须提供自己的System.ResourceManager
。我想有一个基类,如:
public abstract class BaseException : ApplicationException
{
protected abstract static ResourceManager Resources{get;}
public BaseException(System.Enum errorCode, params object[] messageArgs)
: base(ProcessError(errorCode, messageArgs))
{}
private static string ProcessError(Enum errorCode, params object[] messageArgs)
{
string errorMessage = Resources.GetString(errorCode.ToString());
// Handling of messageArgs and trace logging
// ....
return finalError;
}
}
...但我不能有一个抽象的静态方法。有没有更好的办法?
保护覆盖静态<--- !!!!!!警报!!!! – leppie 2008-11-27 12:58:09