.NET MVC 3语义

Dan*_*Dan 5 c# asp.net-mvc-3

我正在阅读一些例子,我在方法之前一直看到[ SOMETHING ]的代码,我想知道它叫什么以及它是如何使用的.

你能定义自己的[ SOMETHING ]还是有定义的这些东西列表?

这里有一些代码示例,我发现使用这个东西,但没有解释它的任何内容.

[HandleError]

public class HomeController : Controller
{

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

有时候他们甚至会把参数放在里面

[HandleError(Order = 2)]

这里发生了什么.我觉得这是超级重要,但没有任何的参考书籍我读过解释他们只是使用它们.

提前谢谢.

doc*_*ess 6

HandleError 是一个属性.

简要介绍属性

属性包含在方括号中,为类,结构,字段,参数,函数和参数添加前缀,您可以通过继承类中的Attribute来定义自己的属性.创建属性的典型格式如下:

public class NameOfYourAttributeAttribute : Attribute {

}
Run Code Online (Sandbox Code Playgroud)

您还可以在属性定义前添加一个属性,该属性定义可应用于的范围:

[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)]
public class NameOfYourAttributeAttribute : Attribute {

}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,除了它只是一个类或结构的装饰器之外,对类的确没有那么多.考虑来自MSDN的示例,其中可以为类提供Author属性(http://msdn.microsoft.com/en-us/library/z919e8tw%28v=vs.80%29.aspx):

[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple = true)]
public class Author : System.Attribute
{
    string name;
    public double version;

    public Author(string name)
    {
        this.name = name;
        version = 1.0;  // Default value
    }

    public string GetName()
    {
        return name;
    }
}

[Author("H. Ackerman")]
private class FirstClass
{
    // ...
}

// There's some more classes here, see the example link...

class TestAuthorAttribute
{
    static void Main()
    {
        PrintAuthorInfo(typeof(FirstClass));
        PrintAuthorInfo(typeof(SecondClass));
        PrintAuthorInfo(typeof(ThirdClass));
    }

    private static void PrintAuthorInfo(System.Type t)
    {
        System.Console.WriteLine("Author information for {0}", t);
        System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // reflection

        foreach (System.Attribute attr in attrs)
        {
            if (attr is Author)
            {
                Author a = (Author)attr;
                System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在HandleError的情况下,具体来说:

它们提供了有用的信息,可以通过反思看到.在这种情况下HandleError,它意味着如果在控制器内抛出任何异常,它将在〜/ Views/Shared /中呈现Error视图.

有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute.aspx.