gpt4 book ai didi

c# - 奇怪的控制流程

转载 作者:行者123 更新时间:2023-11-30 14:59:42 28 4
gpt4 key购买 nike

我正在使用 C# 开发一个框架,该框架将依赖于作为继承基类的类实现的可插入组件。为了使组件尽可能简单,我正在研究一些奇怪的控制流程。

基类包含一个静态方法RunStep(parameter)。该方法被继承类多次调用,每次调用都会检查一个条件。如果这个条件恰好为假,我希望调用方法停止并返回。代码的简化工作版本是:

基类:

class MyBase
{
private static object RunStep(string parameter)
{
if(SomeFunction(parameter))
return SomeOtherFunction(parameter);
else
return null;
}
}

继承类:

class MyInheritor
{
public void Run()
{
object result = RunStep("mystring1");
if(null != result)
{
//perform some logic on result
result = RunStep("mystring2");
if(null != result){
//perform some different logic on result
RunStep("mystring3");
}
}
}
}

我想知道是否可以在基类中做一些事情,以便我可以将继承类简化为:

class MyInheritor2
{
public void Run()
{
object result = RunStep("mystring1");
//perform some logic on result
result = RunStep("mystring2");
//perform some different logic on result
result = RunStep("mystring3");
}
}
}

我会把参数放在一个列表中并循环遍历它们,但是在每次调用 RunStep 方法之后都需要发生一些逻辑,而且每次的逻辑都不同。这消除了表中的循环。另请注意,RunStep 调用之间的逻辑会访问结果的属性,因此它会在没有空检查的情况下崩溃。

这可能看起来是一件微不足道的事情,但可能有成千上万个这样的继承类并简化它们是一件大事。

最佳答案

让基类来控制执行流程:

class Base
{
private readonly List<Tuple<string, Action>> steps = new List<Tuple<string, Action>>();

protected void RegisterStep(string parameter, Action someLogic)
{
steps.Add(Tuple.Create(parameter, someLogic));
}

protected void Run()
{
foreach (var step in steps)
{
var result = RunStep(step.Item1);

if (result == null)
{
break;
}

// perform some logic
step.Item2();
}
}

private object RunStep(string parameter)
{
// some implementation
return null;
}
}

class Derived : Base
{
public Derived()
{
RegisterStep("1", () => { });
RegisterStep("2", () => { });
RegisterStep("3", () => { });

// etc
}
}

关于c# - 奇怪的控制流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16426817/

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