簡體   English   中英

c# 從字符串調用方法

[英]c# call method from string

我有幾個方法叫做 setAnswer1、setAnswer2、setAnswer3 等,我希望能夠使用一些變量在同一個方法中調用每個方法,每次只將最后的數字加一。

到目前為止,我有:

private void button1_Click(object sender, EventArgs e)
{
    string current = "setAnswers" + x;
    Type thisType = this.GetType();
    MethodInfo current = thisType.GetMethod();
    current.Invoke(tihs);
    //MessageBox.Show x;
    setTest();
    if (x <4)
    {
        questionBox.Text = testQuestions[x];
        radioButton1.Text = testAnswers[0];
        radioButton2.Text = testAnswers[1];
        radioButton3.Text = testAnswers[2];
        radioButton4.Text = testAnswers[3];
    }

它調用了幾種方法,例如:

private static void setAnswers1()
{
    string answer1, answer2, answer3, answer4;

    answer1 = "1";
    answer2 = "2";
    answer3 = "3";
    answer4 = "4";
    answer = 3;
    //Store the answers to question one in array.
    testAnswers[0] = answer1;
    testAnswers[1] = answer2;
    testAnswers[2] = answer3;
    testAnswers[3] = answer4;

}

我希望能夠調用和運行幾種方法。

將您的“x”放入發件人。 最簡單的方法是使用標簽屬性。

Button btn = new Button();
btn.Tag = 1;
btn.Click += buttung_click

將所有 Click 方法附加到同一個目標方法,只需使用不同的索引(從 0 開始)。

作為您的 class 的財產

 string[] answers = new string[4] {"1", "2", "3", 4"};
 int[] counter = new int[4];

在你的點擊方法里面

private void button1_Click(object sender, EventArgs e)
{
  int index = (int)((Button)sender).Tag;
  counter[index]++;
  string answer = answers[index];
}

但目前還不清楚你需要什么。 你也可以用同樣的方法構建一個委托數組。

首先,將 setAnswers 方法設為公開
其次,獲取具有您的方法的class的類型,我們稱之為程序

var program = typeof(Program);

然后,使用 GetMethod() 獲取對您的方法的引用

var method = program.GetMethod("setAnswers" + x);

之后,您可以使用 line 調用它

method?.Invoke(program.GetConstructor(Type.EmptyTypes), new object[] { /* Pass any arguments if accepted by the method*/ });

在這種情況下,您也可以使用此行

method?.Invoke(null, null);

希望這會有所幫助。

我認為您正在混淆程序邏輯和程序數據。 你不應該用代碼編寫答案,你應該編寫從(數據庫/文件)讀取答案的代碼


但這里有一個如何避免反射的例子。 反射使它更加復雜和容易出錯。 通過使用反射,在編譯時不會檢查調用,運行軟件時會出錯。 您描述的程序代碼不是動態的。 所有方法都存在於同一個程序中。

您可以為此使用Action數組。 例如:

private Action[] _questions;
private int _currentQuestion;

public void Initialize()
{
    // Fill the array ones with the method pointers. Don't forget to call this.
    _questions = new Action[] { setQuestion1, setQuestion2, setQuestion3, setQuestion4 };
}

public void button1_Click(object sender, EventArgs e)
{
    if (_currentQuestion < 4)
        // execute the Action on the _currentQuesting index.
        _questions[_currentQuestion]();  // <-- add () behind to execute them
    else
        MessageBox.Show("Finished");

    _currentQuestion++;
}

public void setQuestion1()
{
}

public void setQuestion2()
{
}

public void setQuestion3()
{
}

public void setQuestion4()
{
}

就像我說的,我不喜歡混合邏輯和數據,但出於學習目的,這很好。

暫無
暫無

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

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