C# 链接基本构造函数时,如何在重载中重用初始化代码
请参阅下面评论中的问题C# 链接基本构造函数时,如何在重载中重用初始化代码,c#,.net,C#,.net,请参阅下面评论中的问题 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 ini
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;
}
}
我愿意考虑重用基本构造函数并最小化初始化代码的替代实现。我希望将_customField保持为只读,如果提取一个单独的初始化方法,这是不可能的。将其分解为一个单独的方法,并从两个构造函数调用该方法
public CustomException(string customField) : this(customField,"")
{
}
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;
}
}
谢谢,但这是假设基类使用空字符串作为默认值。对于Exception类来说,这可能足够接近,但通常不能保证为真。对于公共CustomException(字符串customField)构造函数,理想情况下不应调用基本构造函数。编译错误:无法将只读字段分配给(构造函数或变量初始值设定项中除外)。正如我在问题中提到的,我想保持字段为只读。@ZaidMasud不,没有编译错误。在
Init
中,\u customField
是一个out
参数,它指的是字段,而不是字段本身。啊。。。现在查看编辑。有趣的语法是将参数同时视为out和not-out。需要对此进行测试。在我的早期版本中,我使用了ref
,这同样适用,但是out
更好。+1用于有趣的语法,这是我以前没有见过的,可以完成任务。这仍然是一种不寻常的方法,如果有更多的参数(x2),Init方法签名的增长速度会比您希望的更快。