簡體   English   中英

如何在 C# 中調用帶有字符串變量的 function

[英]How to call a function with a string variable in C#

我有一個 function,它被賦予了一個字符串,function 調用了它。 我有什么辦法可以使用字符串調用 function 嗎?

void GameLoop()
{ 
  Example("GameLoop")
}

void Example(string functionThatCalledMe)
{
  // Call the method that called this using the string 'functionThatCalledMe'
  Call(functionThatCalledMe);
}

我在Calling a function from a string in C#找到了一個解決方案,我只是不明白它是如何工作的或如何使用它。 似乎還有另一個問題,我無法使用this ,所以我相信它與那個問題有關。

this是指代碼當前運行的實例。

我認為您可能正在將 this.GetType() 添加到 static 方法中。 並且 static 方法未鏈接到實例,因此不起作用。

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

像這樣工作:

this.GetType
//or
typeof(ClassName)

獲取類型,即您可以在運行時使用的 class 定義。

MethodInfo theMethod = thisType.GetMethod(TheCommandString);

嘗試從類型中獲取方法定義。 這可以用來調用(調用)

theMethod.Invoke(this, userParameters);

調用方法定義。 但是由於方法定義不知道它屬於哪個實例,所以你必須傳遞一個實例,以及你希望傳遞的參數。 (不需要參數)

一個例子是:

public static void Main()
{
    var test = new Test();

    Type thisType = test.GetType();
    MethodInfo theMethod = thisType.GetMethod("Boop");
    theMethod.Invoke(test , new object[0]);
}

public class Test
{
    public void Boop()
    {
        Console.WriteLine("Boop");
    }
}

可以看到代碼在:

https://do.netfiddle.net/67ljft

這個解決方案可以解決您的問題嗎?

    class Program
    {
        private static Dictionary<string, Action> _myMethods;

        static Program()
        {
            _myMethods = new Dictionary<string, Action>();
            _myMethods.Add("Greet", Greet);
        }

        static void Main(string[] args)
        {

            InvokeMethod("Greet");
            Console.ReadKey();
        }

        private static void InvokeMethod(string methodNameToInvoke)
        {
            _myMethods[methodNameToInvoke].Invoke();
        }

        private static void Greet()
        {
            Console.WriteLine("Hello there!");
        }
    }

暫無
暫無

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

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