将函数地址(委托)传递给属性

时间:2021-04-05 17:46:43

标签: .net vb.net

我有一个通用的“搜索”窗口,用于多个数据库选择。用户可以从中选择多个记录(通过双击项目并检查它们)。同一个窗口有一个“确定”按钮。此按钮确认从网格中选择。

我想找到一种方法让这个搜索窗口拥有某种属性(即:Public Property ValidateSelectionFunction As ?),它可以从另一个窗口接收委托函数。示例:

Using Search As New SearchWindow
    Search.ValidateSelectionFunction = AddressOf SpecificValidation
    Search.ShowDialog()
End Using

SpecificValidation 将是一个(布尔值)函数,用于验证我对这种特定类型的搜索想要的任何内容。

SearchWindow 将包含如下内容:

Public Class SearchWindow
    Public Property ValidateSelectionFunction As ?

    Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
        If ValidateSelectionFunction IsNot Nothing Then
            Dim Validated As Boolean = ValidateSelectionFunction()
            If Validated Then MsgBox("Validated!")
        End If
    End Sub
End Class

当然这是一个荒谬的例子。这只是为了让我了解我正在努力实现的目标。我正在努力寻找一种方法来为此使用委托。

1 个答案:

答案 0 :(得分:2)

您可以使用 Func<T, TResult> 类型,以便可以分配与签名匹配的任何函数。

一个简化的例子(在 c# 中,因为你已经标记了它)可能看起来像:

public partial class SearchWindow : Form
{
    // This method can be set by the caller to provide a custom validation method
    public Func<string, bool> Validator { get; set; }

    private void Ok_Click(object sender, EventArgs e)
    {
        if (Validator != null)
        {
            // txtInput is a TextBox on the search form that contains the text 
            // we want to validate so we pass that to the validator method 
            bool validated = Validator.Invoke(txtInput.Text);

            if (validated)
            {
                MessageBox.Show("Validated!");
            }
        }
    }
}

然后您的调用代码可能如下所示:

public partial class Form1 : Form
{
    // This is the method that we want to pass to the SearchForm
    private bool CustomValidator(string input)
    {
        // Sample validation that input is 5 characteers
        return input?.Length == 5;
    }

    private void btnSearch_Click(object sender, EventArgs e)
    {
        using (SearchWindow search = new SearchWindow())
        {
            // Assign our private validation method to the search form's property
            search.Validator = CustomValidator;
            search.ShowDialog();
        }
    }
}