c# - 在 Aspx 中分配 C# Lambda Func

标签 c# asp.net delegates func

我有一个自定义控件,我想在其中公开一个方法作为属性(例如,用于自定义验证);

public Func<bool> ValidateMatrixFunc { get; set; }

然后在包含此自定义控件的页面中,我可以使用委托(delegate)或 lambda exp 来分配页面的 OnPreInit 事件;

 protected override void OnPreInit(EventArgs e)
 {
    base.OnPreInit(e);

    ucMatrixTable.ValidateMatrixFunc = ValidateMatrix;
 }

这行得通。

但是,我认为在 aspx 中执行此操作会更方便,如:

<uc1:MatrixTable ID="ucMatrixTable" runat="server" ValidateMatrixFunc="ValidateMatrix" />

但这会崩溃并显示以下消息:

无法从其字符串表示形式“ValidateMatrix”中创建类型为“System.Func`1[[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]”的对象“ValidateMatrixFunc”属性。

所以,我只是想知道……我想知道……是否有忍者知道这个问题的答案,或者这只是我们永远无法解开的生命之谜之一。

最佳答案

您可能希望将“ValidateMatrixFunc”属性公开为事件。为什么?它与控件的通常实现方式更加一致。此外,事件允许您为单个事件拥有多个订阅者(事件处理程序)。虽然这可能不是典型的用例,但有时确实会发生。

我在下面描述了如何将其实现为一个事件:

我们将该事件称为“ValidatingMatrix”。

然后您可以像这样编写 ASPX 标记:

<uc1:MatrixTable ID="ucMatrixTable" runat="server" OnValidatingMatrix="ValidateMatrix" />

此外,让我们使用 CancelEventHandler委托(delegate)而不是 Func<bool> .这意味着代码隐藏中的 ValidateMatrix 方法签名必须如下所示:

protected void ValidateMatrix(object sender, System.ComponentModel.CancelEventArgs e)
{
    // perform validation logic

    if (validationFailed)
    {
        e.Cancel = true;
    }
}

在您的 MatrixTable 自定义控件中,实现如下内容:

    const string ValidatingMatrixEventKey = "ValidatingMatrix";

    public event System.ComponentModel.CancelEventHandler ValidatingMatrix
    {
        add { this.Events.AddHandler(ValidatingMatrixEventKey, value); }
        remove { this.Events.RemoveHandler(ValidatingMatrixEventKey, value); }
    }

    protected bool OnValidatingMatrix()
    {
        var handler = this.Events[ValidatingMatrixEventKey] as System.ComponentModel.CancelEventHandler;
        if (handler != null)
        {
            // prepare event args
            var e = new System.ComponentModel.CancelEventArgs(false);

            // call the event handlers (an event can have multiple event handlers)
            handler(this, e);

            // if any event handler changed the Cancel property to true, then validation failed (return false)
            return !e.Cancel;
        }

        // there were no event handlers, so validation passes by default (return true)
        return true;
    }

    private void MyLogic()
    {
        if (this.OnValidatingMatrix())
        {
            // validation passed
        }
        else
        {
            // validation failed
        }
    }

关于c# - 在 Aspx 中分配 C# Lambda Func,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7753059/

相关文章:

c# - 单一窗体 Windows 窗体应用程序的设计模式

c# - 将套接字服务器从 Node.js 移植到 C#

asp.net - 如何动态修补正在运行的ASP.NET应用程序?

C#: ' += anEvent' 和 ' += new EventHandler(anEvent)' 之间的区别

javascript - JS 或 C# 中的货币转换器

c# - Xamarin 表单错误值不能为空。参数名称 : type

c# - 如何在母版页中设置 View 状态?

c# - 从 Gridview 中的下拉列表中永久删除项目

c# - 是否可以使用 C# 中的委托(delegate)返回方法的代码(作为字符串)?

c# - 我需要等待回调吗?