我试图编写一个程序,其中第1步 - >启动第2步 - >开始步骤3.在每个步骤之间传递变量。
我可以在C#中以这种方式使用事件吗?编写执行此操作的程序的最佳方法是什么?
public class ProgramFlow // the listener program
{
EventArgs args = null;
public delegate void EventHandler(string str, EventArgs e);
public static event EventHandler Step1Reached;
public static event EventHandler Step2Reached;
public ProgramFlow()
{
Step1 step1 = new Step1();
// Print string and kick off Step2
Step2 step2 =new Step2();
// Print String kick off next step
}
}
public class Step1
{
string charRead;
public Step1()
{
Console.Write("Input something for Step1: ");
charRead = Console.ReadLine();
Console.WriteLine();
ProgramFlow.Step1Reached += ProgramFlow_Step1Reached;
}
void ProgramFlow_Step2Reached(string str, EventArgs e)
{
Console.WriteLine(charRead);
}
}
public class Step2
{
string charRead;
public Step2()
{
Console.Write("Input something for Step2: ");
charRead = Console.ReadLine();
Console.WriteLine();
ProgramFlow.Step2Reached += ProgramFlow_Step2Reached;
}
void ProgramFlow_Step2Reached(string str, EventArgs e)
{
Console.WriteLine(charRead);
}
}
class Program
{
static void Main(string[] args)
{
ProgramFlow programFlow = new ProgramFlow();
Console.ReadKey();
}
}
答案 0 :(得分:1)
将步骤接口并使程序流程协调其执行符合您的要求,例如
public class ProgramFlow // the listener program
{
public ProgramFlow()
{
IStep[] steps = new IStep[] { new Step1(), new Step2() };
foreach (var step in steps)
{
step.Step();
step.StepResult();
}
}
}
public interface IStep
{
void Step();
void StepResult();
}
public class Step1 : IStep
{
string stringRead;
public void Step()
{
Console.Write("Input something for Step1: ");
stringRead = Console.ReadLine();
Console.WriteLine();
}
public void StepResult()
{
Console.WriteLine(stringRead);
}
}
public class Step2 : IStep
{
string stringRead;
public void Step()
{
Console.Write("Input something for Step2: ");
stringRead = Console.ReadLine();
Console.WriteLine();
}
public void StepResult()
{
Console.WriteLine(stringRead);
}
}
class Program
{
static void Main(string[] args)
{
ProgramFlow programFlow = new ProgramFlow();
Console.ReadKey();
}
}
答案 1 :(得分:0)
当您希望在不派生新对象的情况下提供可扩展性时,事件将帮助您,并且在您需要执行多个操作时非常有用。当您使用乱序执行时,事件可以提供帮助(尽管异步也可以帮助您)。如果您有任何故障,或者您想要将进度报告回GUI,那么事件是实现这一目标的好方法。
老实说,如果你需要采取行动1,行动2和行动3按顺序发生,如果你只是写下来,代码就不会更简单,更易于维护:
public static void Main()
{
var arg1 = ReadAction1();
Action1(arg1);
var arg2 = ReadAction2();
Action2(arg2);
var arg3 = ReadAction3();
Action3(arg3);
}
那就是说,这会让你走上一条非常紧迫的道路。我想看看你是否可以用OO方式代表你的任务,这样你就可以得到一些你可以换掉并测试的东西。