如果你只是想摆脱参数的构造函数的代码,而不是构造函数本身的 - 给它需要这种类型的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在未正确配置时失败,而不仅仅是默认构造函数认为它足够。 –