標題是有點抽象,所以也許更容易與一個具體的例子來解釋:有沒有辦法在對基類構造函數的調用中使用可覆蓋的行爲?
我發現它有用有我的異常類需要一個枚舉參數,而不是字符串消息。
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