属性是元数据扩展,可在运行时为编译器提供有关程序代码中元素的附加信息。属性用于施加条件或提高代码段的效率。 C#中存在内置属性,但是程序员可以创建自己的属性,这些属性称为Custom属性。要创建自定义属性,我们必须构造从System.Attribute类派生的类。
创建自定义属性的步骤
1.使用AttributeUsageAttribute:此标记定义我们正在构造的属性。它提供信息,例如属性目标是什么,是否可以继承或此属性的多个实例是否存在。 AttributeUsageAttribute具有三个主要成员,如下所示:
- AttributeTargets.All指定可将属性应用于程序的所有部分,而Attribute.Class表示可将属性应用于类,并将AttributeTargets.Method应用于方法。
[AttributeUsageAttribute( AttributeTargets.All )]
- 继承的成员指示该属性是否可以被继承。它需要一个布尔值(真/假)。如果未指定,则默认为true。
[AttributeUsage(AttributeTargets.All, Inherited = false)]
- AllowMultiple成员告诉我们是否可以存在该属性的多个实例。它也需要一个布尔值。默认情况下为false。
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
2.定义Attribute类:以与普通类相同的方式定义,该类的名称通常以’Attribute’结尾。此类必须直接或间接继承自System.Attribute类。
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] public class MyAttribute : Attribute { //Class Members }
3.定义构造函数和属性:构造函数用于设置Attribute类的值,与典型类非常相似。构造函数重载可用于在激发Attribute类对象时处理不同的分配。
public MyAttribute(dataType value) { this.value = value; }
注意:自定义属性也可以为其成员具有诸如get和set之类的属性。
public dataType MyProperty { get {return this.value;} set {this.value = newValue;} }
示例1:以下代码显示了一个名为MyAttribute的自定义属性的示例,该属性具有两个私有成员,即name和action。 “名称”用于为可以应用该属性的任何程序元素定义名称。 “动作”描述了元素应该执行的操作。在这里,这些属性应用于将方法分类为Student的方法。
// C# program to illustrate the // use of custom attributes using System; // Creating Custom attribute MyAttribute [AttributeUsage(AttributeTargets.All)] public class MyAttribute : Attribute { // Provides name of the member private string name; // Provides description of the member private string action; // Constructor public MyAttribute(string name, string action) { this.name = name; this.action = action; } // property to get name public string Name { get { return name; } } // property to get description public string Action { get { return action; } } } class Student { // Private fields of class Student private int rollNo; private string stuName; private double marks; // The attribute MyAttribute is applied // to methods of class Student // Providing details of their utility [MyAttribute("Modifier", "Assigns the Student Details")] public void setDetails(int r, string sn, double m) { rollNo = r; stuName = sn; marks = m; } [MyAttribute("Accessor", "Returns Value of rollNo")] public int getRollNo() { return rollNo; } [MyAttribute("Accessor", "Returns Value of stuName")] public string getStuName() { return stuName; } [MyAttribute("Accessor", "Returns Value of marks")] public double getMarks() { return marks; } } class TestAttributes { // Main Method static void Main(string[] args) { Student s = new Student(); s.setDetails(1, "Taylor", 92.5); Console.WriteLine("Student Details"); Console.WriteLine("Roll Number : " + s.getRollNo()); Console.WriteLine("Name : " + s.getStuName()); Console.WriteLine("Marks : " + s.getMarks()); } }
输出:Student Details Roll Number : 1 Name : Taylor Marks : 92.5
示例2:在此示例中,我们可以显示我们创建的定制属性的内容。在这里,NewAttribute是具有两个字段(即标题和描述)的自定义属性。磁贴存储标题,描述存储应用了NewAttribute的方法的函数。将Custom属性应用于程序任何部分的方法必须在定义之前调用其构造函数。 NewAttribute还包括一个参数化构造函数和一个显示属性内容的方法。在主体中,您使用类名来调用AttributeDisplay方法,因为它是静态方法,它将显示有关应用属性的类的方法的信息。
// C# program to display the custom attributes using System; using System.Reflection; using System.Collections.Generic; // Defining a Custom attribute class class NewAttribute : Attribute { // Private fields private string title; private string description; // Parameterised Constructor public NewAttribute(string t, string d) { title = t; description = d; } // Method to show the Fields // of the NewAttribute // using reflection public static void AttributeDisplay(Type classType) { Console.WriteLine("Methods of class {0}", classType.Name); // Array to store all methods of a class // to which the attribute may be applied MethodInfo[] methods = classType.GetMethods(); // for loop to read through all methods for (int i = 0; i < methods.GetLength(0); i++) { // Creating object array to receive // method attributes returned // by the GetCustomAttributes method object[] attributesArray = methods[i].GetCustomAttributes(true); // foreach loop to read through // all attributes of the method foreach(Attribute item in attributesArray) { if (item is NewAttribute) { // Display the fields of the NewAttribute NewAttribute attributeObject = (NewAttribute)item; Console.WriteLine("{0} - {1}, {2} ", methods[i].Name, attributeObject.title, attributeObject.description); } } } } } // Class Employer class Employer { // Fields of Employer int id; string name; // Constructor public Employer(int i, string n) { id = i; name = n; } // Applying the custom attribute // NewAttribute to the getId method [NewAttribute("Accessor", "Gives value of Employer Id")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute("Accessor", "Gives value of Employer Name")] public string getName() { return name; } } // Class Employee class Employee { // Fields of Employee int id; string name; public Employee(int i, string n) { id = i; name = n; } // Applying the custom // attribute NewAttribute // to the getId method [NewAttribute("Accessor", "Gives value of Employee Id")] public int getId() { return id; } // Applying the custom attribute // NewAttribute to the getName method [NewAttribute("Accessor", "Gives value of Employee Name")] public string getName() { return name; } } class Program { // Main Method static void Main(string[] args) { // Calling the AttributeDisplay // method using the class name // since it is a static method NewAttribute.AttributeDisplay(typeof(Employer)); Console.WriteLine(); NewAttribute.AttributeDisplay(typeof(Employee)); } }
输出:Methods of class Employer getId - Accessor, Gives value of Employer Id getName - Accessor, Gives value of Employer Name Methods of class Employee getId - Accessor, Gives value of Employee Id getName - Accessor, Gives value of Employee Name