我正在读一些例子,我总是在方法之前看到一些代码,我想知道它叫什么,它是如何使用的。
你能定义你拥有的东西吗?或者有这些东西的定义列表?
下面是我发现的一些代码示例,它们使用这个东西,但是没有解释任何有关它的内容。
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
}有时他们甚至把参数放进里面,就像
HandleError(Order = 2)
这是怎么回事。我觉得这是非常重要的超级,但是我读过的参考书中没有一本解释过,他们只是使用它们。
提前谢谢。
发布于 2011-10-05 19:12:18
HandleError是一个属性。
简要介绍属性
属性包含在方括号、前缀类、结构、字段、参数、函数和参数中,您可以通过继承类中的属性来定义自己的属性。创建属性的典型格式如下:
public class NameOfYourAttributeAttribute : Attribute {
}您还可以在属性定义前面加上一个属性,该属性定义它可以应用于的内容的范围:
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)]
public class NameOfYourAttributeAttribute : Attribute {
}在上面的例子中,除了作为一个类或一个结构的装饰者之外,这个类实际上没有那么多。考虑一个来自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);
}
}
}
}在HandleError的例子中,特别是:
它们提供了有用的信息,可以通过反射看到。在HandleError的情况下,这意味着如果在控制器内抛出任何异常,它将在~/ view /Shared/中呈现错误视图。
有关更多详细信息,请参阅http://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute.aspx。
发布于 2011-10-05 19:11:38
它们被称为属性,并且是C#的一个共同特性。你可以自己申报:
class SomeAttr : Attribute
{
}发布于 2011-10-05 19:13:36
它们被称为属性,它们只是从Attribute派生出来的普通类。你当然可以定义你自己的。
因为MVC是以约定而不是配置为思想的,所以您可以用属性来修饰您的函数,并且框架将尝试找出如何处理它们,而不需要您的任何干预。
例如,如果您用[HttpGet]来修饰您的函数,那么只有GET请求才会通过它被路由,其他任何东西(比如POST)都会查找另一个函数,或者如果没有其他功能,则抛出一个错误。
https://stackoverflow.com/questions/7666364
复制相似问题