[]运算符用于指定属性.在此指定的属性用反射技术对属性进行查询,也可以说是非托管的静态方法入口
对于类似于这样的说明标记
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethod
Type.Delete, true)]
该标记不起任何实际作用,仅是告诉vs该语句下面的方法(Method)是ObjectDataSource的默认绑定方法
标记的作用是为了让编译器更好的为ObjectDatasource向导找到合适的方法
使用反射访问属性 ...
[]运算符用于指定属性.在此指定的属性用反射技术对属性进行查询,也可以说是非托管的静态方法入口
对于类似于这样的说明标记
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethod
Type.Delete, true)]
该标记不起任何实际作用,仅是告诉vs该语句下面的方法(Method)是ObjectDataSource的默认绑定方法
标记的作用是为了让编译器更好的为ObjectDatasource向导找到合适的方法
使用反射访问属性
如果没有检索自定义属性的信息和对其进行操作的方法,则定义自定义属性并将其放置在源代码中就没有意义。C# 具有一个反射系统,可用来检索用自定义属性定义的信息。主要方法是 GetCustomAttributes,它返回对象数组,这些对象在运行时等效于源代码属性。此方法具有多个重载版本。有关更多信息,请参见 Attribute。
属性规范,如:
[Author("H. Ackerman", version = 1.1)]
class SampleClass
在概念上等效于:
Author anonymousAuthorObject = new Author("H. Ackerman");
anonymousAuthorObject.version = 1.1;
但是,直到查询 SampleClass 以获取属性时才会执行此代码。对 SampleClass 调用 GetCustomAttributes 会导致按上述方式构造并初始化一个 Author 对象。如果类还有其他属性,则其他属性对象的以类似方式构造。然后 GetCustomAttributes 返回 Author 对象和数组中的任何其他属性对象。之后就可以对此数组进行迭代,确定根据每个数组元素的类型所应用的属性,并从属性对象中提取信息。
示例
下面是一个完整的示例。定义一个自定义属性,将其应用于若干实体并通过反射进行检索。
X8023Z
1 [System.AttributeUsage(System.AttributeTargets.Class |
2 System.AttributeTargets.Struct,
3 AllowMultiple = true) // multiuse attribute
4 ]
5 public class Author : System.Attribute
6 {
7 string name;
8 public double version;
9
10 public Author(string name)
11 {
12 this.name = name;
13 version = 1.0; // Default value
14 }
15
16 public string GetName()
17 {
18 return name;
19 }
20 }
21
22 [Author("H. Ackerman")]
23 private class FirstClass
24 {
25 //
26 }
27
28 // No Author attribute
29 private class SecondClass
30 {
31 //
32 }
33
34 [Author("H. Ackerman"), Author("M. Knott", version = 2.0)]
35 private class ThirdClass
36 {
37 //
38 }
39
40 class TestAuthorAttribute
41 {
42 static void Main()
43 {
44 PrintAuthorInfo(typeof(FirstClass));
45 PrintAuthorInfo(typeof(SecondClass));
46 PrintAuthorInfo(typeof(ThirdClass));
47 }
48
49 private static void PrintAuthorInfo(System.Type t)
50 {
51 System.Console.WriteLine("Author information for {0}", t);
52 System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t); // reflection
53
54 foreach (System.Attribute attr in attrs)
55 {
56 if (attr is Author)
57 {
58 Author a = (Author)attr;
59 System.Console.WriteLine(" {0}, version {1:f}", a.GetName(), a.version);
60 }
61 }
62 }
63 }
64
输出
Author information for FirstClass
H. Ackerman, version 1.00
Author information for SecondClass
Author information for ThirdClass
H. Ackerman, version 1.00
M. Knott, version 2.00