c#在自定义属性中执行代码

Pet*_*ter 5 c# asp.net-mvc attributes runtime

可能重复:
为什么我的.NET属性不执行操作?

嗨,

这可能听起来像一个非常愚蠢的问题,我不知道这里有什么可能,因为网上的所有"自定义属性"教程几乎都是相同的,并且它们没有解决我想要做的事情.我已经看到了一些代码在代码中写入属性类的代码,例如:使用ASP.NET MVC Action Filters进行日志记录,我想知道这个代码是如何执行的.

如果我有以下代码:

public class Test
{
    [RestrictedAttribute("RegisteredMember")]
    public void DoSomething()
    {
        //this code can only be executed if the logged-in user
        //is a member of the RegisteredMember group
    }
}
Run Code Online (Sandbox Code Playgroud)

然后自定义Attribute RestrictedAttribute将是这样的:

[AttributeUsage(AttributeTargets.Method)]
public class RestrictedAttribute : System.Attribute 
{
    /// <summary>
    /// Make this code restricted to users with a required role
    /// </summary>
    /// <param name="requiredRole">The role required to execute this method</param>
    public RestrictedAttribute(string requiredRole)
    {
        //validate if member is in role, else throw exception
        throw new MemberNotInRoleException(requiredRole);
    }
    public new string ToString() {
        return "Access needs to be granted";
    }

}
Run Code Online (Sandbox Code Playgroud)

现在的问题是,当我执行Test.DoSomething()方法时,我无法抛出MemberNotInRoleException.

也许我只是错过了自定义属性的整个概念,随便解释一下.

Mar*_*son 3

您查看属性的方式乍一听起来是正确的,但请再想一想。你真正要做的是装饰你的类或其他什么东西,以便与它一起工作的东西可以做出决定,而不是让类本身可以做出决定。对于我来说,在 MVC 中使用 actionfilter 属性的方式让我感到困惑,这看起来像是它们做了一些事情,但它是挑选事件并相应地使用属性的框架。我通常尝试将属性视为我的程序要使用的注释。