Home  >  Article  >  Backend Development  >  How to construct custom properties in C#?

How to construct custom properties in C#?

王林
王林forward
2023-08-31 22:37:021259browse

How to construct custom properties in C#?

#Attributes are used to add metadata to a program, such as compiler directives and other information such as comments, descriptions, methods, and classes.

.Net Framework allows the creation of custom properties that can be used to store declarative information that can be retrieved at runtime.

New custom attributes are derived from the System.Attribute class.

//a custom attribute BugFix to be assigned to a class and its members
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

public class DeBugInfo : System.Attribute

Let us construct a custom property called DeBugInfo that stores information obtained by debugging any program.

The DeBugInfo class has three private properties for storing the first three pieces of information, and one public property for storing the message. Therefore, the bug number, developer name, and review date are positional parameters of the DeBugInfo class, and the message is an optional or named parameter.

Example

Let's see how -

//a custom attribute BugFix to be assigned to a class and its members
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]

public class DeBugInfo : System.Attribute {
   private int bugNo;
   private string developer;
   private string lastReview;
   public string message;

   public DeBugInfo(int bg, string dev, string d) {
      this.bugNo = bg;
      this.developer = dev;
      this.lastReview = d;
   }

   public int BugNo {
      get {
         return bugNo;
      }
   }

   public string Developer {
      get {
         return developer;
      }
   }

   public string LastReview {
      get {
         return lastReview;
      }
   }
   public string Message {
      get {
         return message;
      }

      set {
         message = value;
      }
   }
}

The above is the detailed content of How to construct custom properties in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete