2

我有一个执行各种任务的类库。我希望其中一些任务响应来自 Windows 窗体的用户输入而发生。到目前为止,我尝试的是在库中设置一个输入接口,如下所示:

public interface IInputter
{
    string sendInput();
}

以如下形式实现接口:

 public partial class Form1 : Form,IInputter
    {
        string sentText=null;

        public Form1()
        {
            InitializeComponent();
        }

        public string sendInput()
        {
            string inputText=sentText;
            sentText=null;
            return inputText;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Excel files (*.xls*)|*.xls*";
            DialogResult dr = ofd.ShowDialog();
            if (dr == DialogResult.OK)
            {
                sentText = ofd.FileName; 
            }
        }
    }

从表单代码调用库函数时,将表单作为参数传递:

public partial class StartForm : Form
{
    public StartForm()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        f1.Show();
        Main main = new Main();
        main.main(f1);
    }
}

然后从库函数中调用输入函数:

    public string main(IInputter inputter)
    { 
     do
     {
        testBk = inputter.sendInput();
     }
     while (testBk == null);
     return testBk;
    }

但是,Form1不是满载;控件应该在的地方只有空白,因此While循环只是无限运行,而表单无法通过函数将输入发送到库IInputter.sendInput()函数。

我确信必须有一种更“内置”的方式来设置可以从其接口以表单实现的库中访问的数据流;我错过了什么?

4

1 回答 1

4

您的表单是交互式的,因此您的界面会更有意义地公开事件

public interface IInputter
{
    event EventHandler<InputReceivedEventArgs> ReceivedInput;
}

public class InputReceivedEventArgs : EventArgs
{
    public InputReceivedEventArgs(string text)
    {
        this.Text = text;
    }

    public string Text { get; private set; }
}

public partial class Form1 : Form, IInputter
{
    public event EventHandler<InputReceivedEventArgs> ReceivedInput = delegate { };


    private void button1_Click(object sender, EventArgs e)
    {
        var dialog = new OpenFileDialog { Filter = "Excel files (*.xls*)|*.xls*" };
        var dialogResult = dialog.ShowDialog();
        if (dialogResult == DialogResult.OK)
        {
            ReceivedInput(this, new InputReceivedEventArgs(ofd.FileName));
            sentText = ofd.FileName; 
        }
    }
}

然后,消费:

public string main(IInputter inputter)
{
    string receivedInput = null;

    inputter.ReceivedInput += (s, e) => YourLibrary.DoSomething(e.Text);
}
于 2013-06-03T22:09:42.883 回答