簡體   English   中英

需要幫助來了解我的C#控制台應用程序中的動態菜單

[英]Need help understanding dynamic menus in my C# console application

我正在嘗試設計一個控制台應用程序,其中的菜單是從某種數據結構生成的,並且每個菜單項都可以指定一個處理程序/操作(可能只是顯示一個不同的菜單)。 抱歉,這聽起來已經很麻煩了!

我在找出正確的方法上遇到了很多麻煩。 這是我的第一個C#應用程序,我覺得我已經讀了幾個小時的委托書了,但我仍然不確定是否應該使用它們。

我有很多現有的代碼,但是我覺得如果在嘗試修復基礎方面可能遇到的問題之前獲得一些總體指導可能會更好。 我將嘗試描述我要做什么:

  • 具有由菜單標題和任意數量的菜單項組成的“菜單”類。
  • 每個“ MenuItem”由一個熱鍵,描述和“指向處理程序的指針”組成。
  • 處理程序完成工作,然后返回菜單。

這是我遇到的“指向處理程序的指針”。 此處理程序應如何在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>將接受一個將intchar作為輸入但返回string 你從Visual Studio的一些幫助-在委托說明它顯示inout詞語的參數前面的信號無論是輸入或輸出參數。

現在,創建了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);
    }
}

請注意,這只是您問題的非常基本的起點。 但是,它允許您創建菜單項並為這些項分配不同的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM