以下实例,定义了一个自定义特性Author、将其应用于多个实体,并通过反射对其进行检索。本实例代码使用了顶级语句,须在.NET 5(C# 9.0)以上环境中使用。
Console.WriteLine("Hello, Hovertree!This is a sample of Attribute.");//顶级语句,须在.NET 5(C# 9.0)以上环境中使用
TestAuthorAttribute.Test();
Console.ReadLine();
// Multiuse attribute.
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct,
AllowMultiple = true) // Multiuse attribute.
]
public class Author : System.Attribute
{
string name;
public double version;
public Author(string name)
{
this.name = name;
// Default value.
version = 1.0;
}
public string GetName()
{
return name;
}
}
// Class with the Author attribute.
[Author("W. Hovertree")]
public class FirstClass
{
// ...
}
// Class without the Author attribute.
public class SecondClass
{
// ...
}
// Class with multiple Author attributes.
[Author("H. Ackerman"), Author("R. Koch", version = 2.0)]
public class ThirdClass
{
// ...
}
class TestAuthorAttribute
{
public static void Test()
{
PrintAuthorInfo(typeof(FirstClass));
PrintAuthorInfo(typeof(SecondClass));
PrintAuthorInfo(typeof(ThirdClass));
}
private static void PrintAuthorInfo(System.Type t)
{
System.Console.WriteLine("Author information for {0}", t);
// Using reflection.
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t); // Reflection.
// Displaying output.
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);
}
}
}
}
/*
调用TestAuthorAttribute类的Test()方法的输出如下:
Hello, Hovertree!This is a sample of Attribute.
Author information for FirstClass
W. Hovertree, version 1.00
Author information for SecondClass
Author information for ThirdClass
H. Ackerman, version 1.00
R. Koch, version 2.00
*/
运行效果如下图:
