请参阅嵌入在下面的评论的问题。
Please see question embedded in comment below.
public class CustomException : Exception
{
private readonly string _customField;
public CustomException(string customField, string message)
: base(message)
{
// What's the best way to reuse the customField initialization code in the
// overloaded constructor? Something like this(customField)
}
public CustomException(string customField)
{
_customField = customField;
}
}
我愿意考虑重新使用基构造,并尽量减少初始code替代实现。我想保持_customField只读,如果我提取一个单独的初始化方法,这是不可能的。
I'm open to considering alternative implementations that reuse the base constructor and minimize initialization code. I'd like to keep the _customField readonly, which is not possible if I extract a separate initialization method.
因子它成一个单独的方法,并调用该方法从两个构造函数。
Factor it out into a separate method, and call that method from both constructors.
public class CustomException : Exception
{
private readonly string _customField;
public CustomException(string customField, string message)
: base(message)
{
Init(out _customField, customField);
}
public CustomException(string customField)
: base()
{
Init(out _customField, customField);
}
private Init(out string _customField, string customField)
{
_customField = customField;
}
}