5
public class GroupWithSpecificOptionsNotFoundException : Exception
{
public GroupWithSpecificOptionsNotFoundException(string place, Dictionary<string, string> options)
: base(string.Format("Group with specific options not found, in ({0}), at ({1})", place, DateTime.Now.ToString()))
{
foreach (string key in options.Keys)
{
this.Message += string.Format("Option Name : ({0}) with Value : ({1}) not found in this group options set", key, options[key]);
}
}
}
想法很簡單,我想將鍵/值對象包含到異常的Message
。此操作不能在base()
事件中執行,也不能在構造函數中執行(「消息是隻讀的」)。自定義消息屬性的繼承異常類
我找到了一個解決方案,其中靜態函數可以做的伎倆:
public class GroupWithSpecificOptionsNotFoundException : Exception
{
public static string GenerateOptionValueString(Dictionary<string, string> options)
{
string msg = string.Empty;
foreach (string key in options.Keys)
{
msg += string.Format("Option Name : ({0}) with Value : ({1}) not found in this group options set", key, options[key]);
}
return msg;
}
public GroupWithSpecificOptionsNotFoundException(string place, Dictionary<string, string> options)
: base (string.Format("Group with specific options not found ({2}), in ({0}), at ({1})",
place, DateTime.Now.ToString(), GroupWithSpecificOptionsNotFoundException.GenerateOptionValueString(options)))
{
}
}
但我不是很滿意吧! 是否有任何其他解決此類和類似的情況?