将方法组作为参数传递

时间:2018-03-07 07:46:58

标签: c# methods delegates

我在C#中创建自定义输入对话框。我的输入对话框有多个输入字段(由构造函数指定),并在提交时将所有输入传递给委托方法。

我还希望调用者能够通过参数将方法发送到输入对话框。但是,我在解决这个问题时遇到了一些麻烦。这是我的代码:

InputDialogue类:

public class InputDialogue {
    public static InputDialogue ins;
    public delegate void Foo(string[] input);
    public Foo doThisWithTheData;
    public InputField[] fields;

    public static void Query(string title, string[] fields, MethodToCall m)
    {
        // display the dialogue, allowing the user to input data into the fields
        doThisWithTheData = m;
    }

    public void Submit()
    {
        List<string> input = new List<string>();
        foreach (InputField i in ins.fields)
        {
            input.add(i);
        }
        doThisWithTheData(input.ToArray());
    }
}

我想作为参数传递的方法:

    public class UserProfile 
    {
        public static void Login(string[] input)
        {
            string user = input[0];
            string pass = input[1];
            ValidateCredentials();
        }

        public void ChangeName(string[] input)
        {
            if (ValidatePassword(new string[] { input[0] }))
            {
                name = input[1];
                WriteToFile();
            }
            else
                MessageDialog.Set("Error", "Invalid password.");
        }

        public void ChangePassword(string[] input)
        {
            if (ValidatePassword(new string[] { input[0] }))
            {
                password = input[1];
                WriteToFile();
            }     
            else
                MessageDialog.Set("Error", "Incorrect password"); 
        }
    }

一些示例调用语句:

    InputDialogue.Query("Login", new string[] { "Name", "Password" }, UserProfile.Login);
    InputDialogue.Query("Change Name", new string[] { "New Name", "Password" }, UserProfile.ChangeName);
    InputDialogue.Query("Change Password", new string[] { "Current Password", "New Password" }, UserProfile.ChangePassword);

我知道我可以简单地让调用者手动设置doThisWithTheData,这在技术上可行,但我想将这一切包装在一个方法中。因此,我的主要问题是我如何将我的方法作为参数传递给Query。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

// declare a delegate, or use Action<string[]>
public delegate void MethodToCall (string[] input);

public class InputDialogue 
{     
    // the public here is questionable, esp for a delegate
    public MethodToCall doThisWithTheData;  
    public InputField[] fields;

    public static void Query(string title, string[] fields, MethodToCall m)
    {
        // display the dialogue, allowing the user to input data into the fields
        doThisWithTheData = m;
    }
    ....
}