我正在尝试设计一个控制台应用程序,其中的菜单是通过某种数据结构生成的,并且每个菜单项都可以指定一个处理程序/操作(可能只是显示一个不同的菜单)。抱歉,这听起来已经很令人费解了!
我在寻找解决此问题的正确方法时遇到了很多麻烦。这是我的第一个C#应用程序,感觉好像我已经读了几个小时的委托书了,但我什至不确定我是否应该使用它们。
我有很多现有的代码,但是我觉得如果在尝试修复基础方面可能遇到的问题之前获得一些总体指导可能会更好。我将尝试描述我要做什么:
这是我遇到的“指向处理程序的指针”。此处理程序应如何在MenuItem对象中表示?如何从菜单提示中调用处理程序?我会以完全错误的方式进行操作吗?
希望这是有道理的:)
我认为代表们可能是一个很好的起点。首先,由于它们在C#中相当流行,并且由于您开始学习C#,因此这是一个很好的做法。其次,使用委托来实现您的应用程序应该非常简单。
让我们考虑一下Action<T>
和Func<T>
代表。第一个可以执行某些操作,但不会返回任何值。第二个返回一个类型T的值。这两种类型最多可以包含16个参数。基本上,它们的主要行为是成为方法的占位符。
因此,让我们看一下嵌入在您的应用程序上下文中的一些示例:
public class MenuItem<T>
{
public string Description { get; set; }
public char HotKey { get; set; }
public Func<T> FirstHandler { get; set; } // returns some value
public Action<T> SecondHandler { get; set; } // does not return any value
// let's use this method to invoke the first handler
public T DoSomething()
{
// this handler is of type Func<T> so it will return a value of type T
return this.FirstHandler.Invoke();
}
// let's use this method to invoke the second handler
public void DoSomethingElse(T input)
{
this.SecondHandler.Invoke(input);
}
}
在的情况下,Func
如果有比上一个以上的说法是返回类型。其他是输入类型。因此,例如,Func<int, char, string>
将接受采用int
和char
作为输入但返回的方法string
。您可以从Visual Studio中获得一些帮助-它在委托描述中显示,in
并out
在参数前面显示单词以表示它是输入参数还是输出参数。
现在,有了MenuItem
创建的类,您可以通过以下方式使用它:
class Program
{
// A method that takes no input arguments but returns string
private static string ReturnHelloWorld()
{
return "Hello World";
}
static void Main(string[] args)
{
MenuItem<string> menuItem = new MenuItem<string>();
// FirstHandler signature is Func<T>
// So it doesn't take any input arguments
// and returns T - in our case string
menuItem.FirstHandler = ReturnHelloWorld;
// SecondHandler signature is Action<T>
// So it takes one input argument of type T (here, string)
// and returns void
menuItem.SecondHandler = Console.WriteLine;
// Now use a method of MenuItem class to invoke FirstHandler.
string menuItemMessage = menuItem.DoSomething();
// Use another method to invoke SecondHandler.
menuItem.DoSomethingElse(menuItemMessage);
}
}
请注意,这只是您问题的一个非常基本的起点。但是,它允许您创建菜单项并为这些项分配不同的行为。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句