允许或禁止在.NET中运行方法

Ale*_*der 3 c# reflection methods attributes

我需要在一个类中组织一些简单的安全性取决于枚举的值.我能想到的只是在方法上使用属性然后运行检查然后如果失败则抛出异常.样品:

    [ModulePermission(PermissonFlags.Create)]
    public void CreateNew()
    {
        CheckPermission();
        System.Windows.Forms.MessageBox.Show("Created!");
    }
    protected void CheckPermission()
    {
        var method = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod();
        if (!flags.HasFlag(method.GetCustomAttributes(true).Cast<ModulePermissionAttribute>().First().Flags))
        {
            throw new ApplicationException("Access denied");
        }
    }
Run Code Online (Sandbox Code Playgroud)

是否有更优雅或简单的方法来执行此操作,就像在方法运行时触发事件一样?

Nic*_*era 6

为什么不使用标准的代码访问安全性而不是重新实现属性处理和堆栈行走?

我认为,如果您阅读链接文档,您将看到您所拥有的内容与实现实际安全性所需的内容无关.值得庆幸的是,这种问题已经得到解决?