gpt4 book ai didi

c# - 责任链 - Servicer1 不调用 Servicer2

转载 作者:太空宇宙 更新时间:2023-11-03 15:29:02 27 4
gpt4 key购买 nike

我试图通过在 Servicer 类字符串中搜索字符/字符串来演示责任链模式的使用。代码运行但 Servicer1 ServiceReq 未调用 Servicer2 ServiceReq。如果我用“g”运行它,我只会得到“Checked Servicer1”,但我应该得到“Checked Servicer1”“Request found in Servicer 2”。

MainApp.cs
namespace ChainOfResponsibility
{
abstract class Servicer
{
protected Servicer successor;

public void SetSuccessor( Servicer s)
{
successor = s;
}
public abstract string ServiceReq(char request);
}

class Servicer1 : Servicer
{
public override string ServiceReq(char request)
{
string s1 = "Sam ate nuts";
if (s1.Contains(request))
{
return "Request found in Servicer 1";
}
else if (successor != null)
{
successor.ServiceReq(request);
}
return "Checked Servicer1'";
}
}

class Servicer2 : Servicer
{
public override string ServiceReq(char request)
{
string s2 = "Apples are great";
if (s2.Contains(request))
{
return "Request found in Servicer 2";
}
else if (successor != null)
{
successor.ServiceReq(request);
}
return "Checked Servicer 2";
}
}

表单代码:

namespace ChainOfResponsibility
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
char request = System.Convert.ToChar(textBox1.Text);
Servicer h1 = new Servicer1();
Servicer h2 = new Servicer2();
h1.SetSuccessor(h2);

AddToList(h1.ServiceReq(request));
}
private void AddToList(string message)
{
listBox1.Items.Add(message);

listBox1.Items.Add("----------------------------------------");

if (listBox1.Items.Count > 0)
listBox1.TopIndex = listBox1.Items.Count - 1;
}
}
}

最佳答案

第一个问题是你永远不会对 successor.ServiceReq 的返回值做任何事情。 .下一个问题是您似乎想要从 ServiceReq 返回多条消息。 .为此,您应该将返回类型设置为 IEnumerable<string> ,并对您的代码进行相应的调整。

这里是你将如何调整你的“服务者”:

abstract class Servicer
{
...
public abstract IEnumerable<string> ServiceReq(char request);
}

class Servicer1 : Servicer
{
public override IEnumerable<string> ServiceReq(char request)
{
string s1 = "Sam ate nuts";
yield return "Checked Servicer1";
if (s1.Contains(request))
{
yield return "Request found in Servicer 1";
}
else if (successor != null)
{
yield return successor.ServiceReq(request);
}
}
}

// Similar changes for Servicer2

下面是您的表单代码的更改:

namespace ChainOfResponsibility
{
public partial class Form1 : Form
{
...
private void AddToList(IEnumerable<string> messages)
{
listBox1.Items.AddRange(messages);

...
}
}
}

如果您在文本框中输入了适当的字符,这将生成包含您预期输出的列表。

关于c# - 责任链 - Servicer1 不调用 Servicer2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275094/

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