gpt4 book ai didi

c# - 编程策略——如何将对象向下传递到类链中

转载 作者:行者123 更新时间:2023-11-30 15:40:50 24 4
gpt4 key购买 nike

我正在努力改进使用类和对象的策略。

将对象向下传递到特定类链以保持代码井井有条的最佳方式是什么。

示例:使用 ZedGraph 对象(注意)这可能不是最好的示例,但它会让想法得到理解。

class Graphhandler
{
private ZedGraphControl ZGC;
private SubGraphController PortionofGraph;

public class GraphHandler(ZedGraphControl _ZGC)
{
ZGC = _ZGC;
initializeGraph();
}

private void initializeGraph()
{
// notice I am putting the ZGC Object into another class
// and likely that ZGC object will go into another class
PortionofGraph = new SubGraphController(ZGC);
}
}

class SubGraphController
{
private ZedGraphControl ZGC;
private DeeperSubGraphController PortionofGraph;

public class SubGraphController(ZedGraphControl _ZGC)
{
ZGC = _ZGC;
initializeSubGraph();
}

private void initializeSubGraph()
{
PortionofGraph = new DeeperSubGraphController(ZGC);
// is there a better way?
}

}

有没有更好的方法通过所有这些调用向下传递 yop 级别对象来操作数据?

最佳答案

通常,答案是将完全形成的依赖项传递到您的对象中。例如:

public GraphHandler(SubGraphController portionOfGraph) {
this.portionOfGraph = portionOfGraph;
}

public SubGraphController(DeeperSubGraphController portionOfGraph) {
this.portionOfGraph = portionOfGraph;
}


...

var zedGraphControl = new ZedGraphControl();
var deeperSubGraphController = new DeeperSubGraphController(zedGraphControl);
var subGraphController = new SubGraphController(deeperSubGraphController);
var graphHandler = new GraphHandler(subGraphController);

而不是直接在子图 Controller 中构造 DeeperSubGraphController。如今,您通常使用依赖注入(inject)框架来协调所有这些。

(另请参阅:Dependency Injection Myth: Reference Passing)

关于c# - 编程策略——如何将对象向下传递到类链中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8858521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com