【问题标题】:Winforms method/event filter attributeWinforms 方法/事件过滤器属性
【发布时间】:2014-05-25 10:21:36
【问题描述】:

我已经使用 ASP.NET MVC 一年多了。我喜欢 ASP.NET MVC。与此同时,我时不时地开发一个 Windows 窗体应用程序。此应用程序允许我们的客户为其网上商店创建组结构。

为此,我使用TreeView。这与 ASP.NET MVC 有何关系?嗯,MVC 具有这些非常方便的操作过滤器属性,并且使代码更具可读性(在我看来)。我的意思是过滤器,例如 [Authorize] 属性,如果用户未获得授权,它会停止执行操作。

所以实际的问题是,能否为 Windows 窗体应用程序中的方法和事件创建一个模拟过滤器?我需要检查(在很多方法和事件中)SelectedNodeTreeView 属性是否有值。现在我这样做:

private void setSelectedGroupInformation(bool refreshProductCount)
{
    GroupNode selectedNode = trvGroupTree.SelectedNode;
    if (selectedNode == null || !selectedNode.HasGroup)
        return;

    // Code that actually DOES something
}

但如果可以的话,那就太好了:

[SelectedNodeRequired]
[GroupRequired]
private void setSelectedGroupInformation(bool refreshProductCount)
{
    // Code that actually DOES something
}

这样可读性更好。我在网上查了一下,但找不到类似的问题。

【问题讨论】:

    标签: c# winforms filter attributes


    【解决方案1】:

    这可能很好,但您需要为此做一些工作(例如,在运行时构造一个类型)。比较简单的就是先调用一些常用的方法

    [SelectedNodeRequired]
    [GroupRequired]
    private void setSelectedGroupInformation(bool refreshProductCount)
    {
        if(MethodTester())
            return;
        // Code that actually DOES something
    }
    
    bool MethodTester()
    {
        // use call stack to get caller method name
        // use reflection to get attributes of method
        // check attributes and conditions
        ...
        return true; // if has to be filtered
        ...
        return false;
    }
    

    但是,为什么不让方法实际上是你需要检查的所有逻辑呢?像这样

    private void setSelectedGroupInformation(bool refreshProductCount)
    {
        if(Global.IsGroupRequired && Global.IsSelectedNodeRequired)
        {
            // Code that actually DOES something
        }
    }
    

    【讨论】:

    • 感谢您的回答。那么没有内置的方法可以做到这一点吗?我喜欢你的第一种方法!如果没有方法中的 if 语句,就没有办法做到这一点?
    猜你喜欢
    • 2018-01-09
    • 2011-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多