如果你只是想擺脫參數的構造函數的代碼,而不是構造函數本身的 - 給它需要這種類型的deserialisation的 - 你可以刪除這兩個構造和使用一個工廠方法來創建節點。這將導致類有一個默認的公共構造函數。
例如,更改:
public class FancyNode : Node
{
private IController controller;
public string ID
{
get;
private set;
}
// I would really like to get rid of this constructor
public FancyNode()
{
throw new NotSupportedException();
}
// NOTICE: no default constructor here
public FancyNode(IController controller, string id)
{
this.controller = controller;
this.ID = id;
}
}
到:
public class FancyNode : Node
{
private IController controller;
public string ID
{
get;
private set;
}
public static FancyNode CreateNode(IController controller, string id)
{
var node = new FancyNode();
node.controller = controller;
node.ID = id;
return node;
}
}
是你失去了嚴格的控制,你有不允許不經過那些要創建的對象參數,鑑於任何人現在可以做var x = new FancyNode()
。然後再次驗證參數,因此使用new FancyNode(null, null)
調用它沒有任何區別。
不錯的想法,但是我不想從代碼中移除構造函數,我根本不需要默認的構造函數。我想讓YamlDotNet在未正確配置時失敗,而不僅僅是默認構造函數認爲它足夠。 –