C # write custom features (attribute) Detailed description (from: http://www.csharpwin.com/csharpspace/9349r9836.shtml)

Source: Internet
Author: User

 

  • Abstract: This article introduces C # Coding Custom Attributes. Custom Attributes are essentially traditional classes derived directly or indirectly from system. attribute. Like traditional classes, custom attributes also contain methods for storing and retrieving data.

To design your own custom attributes, you do not have to master many new concepts. If you are familiar with object-oriented programming and know how to design classes, you already have most of the required knowledge. Custom Attributes are essentially traditional classes derived directly or indirectly from system. attribute. Like traditional classes, custom attributes also contain methods for storing and retrieving data.

The main steps to correctly design custom attribute classes are as follows:

  • Apply attributeusageattribute

  • Declare Attribute Class

  • Declare Constructors

  • Declare attributes

This section describes each of the preceding steps and ends with a custom property example.

Apply attributeusageattribute

Custom attribute declarationAttributeusageattributeThe attribute defines some main attributes of the attribute class. For example, you can specify whether an attribute can be inherited by another class or what elements can be applied to a property. The following code snippet illustrates how to useAttributeusageattribute.

[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]

The system. attributeusageattribute class contains three important members for creating custom attributes: attributetargets, inherited, and allowmultiple.

Attributetargets Member

In the previous exampleAttributetargets. AllIndicates that the property can be applied to all program elements. You can also specifyAttributetargets. ClassIndicates that the attribute can only be applied to a class; orAttributetargets. MethodIndicates that the property can only be applied to a method. All program elements can be marked by custom attributes in this way to describe them.

You can also pass multiple attributetargets instances. The following code snippet specifies that custom attributes can be applied to any class or method.

[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method)]
Inherited attributes

The inherited attribute indicates whether a property can be inherited from a class applied to it. This attribute usesTrue(Default) orFalseFlag. For example, in the following code example,MyattributeBy defaultInheritedThe value isTrue, AndYourattributeOfInheritedThe value isFalse.

//This defaults to Inherited = true.
public class MyAttribute :Attribute
{
}

[AttributeUsage( Inherited = false)]
public class YourAttribute : Attribute
{
}

Then, these two attributes are applied to the base class.Myclass.

public class MyClass
{
[MyAttribute]
[YourAttribute]
public virtual void MyMethod()
{
//...
}
}

Finally,YourclassClass slave base classMyclassInheritance. MethodMymethodDisplayMyattributeInsteadYourattribute.

public class YourClass: MyClass
{
//MyMethod will have MyAttribute but not YourAttribute.
public override void MyMethod()
{
//...
}

}
Allowmultiple attributes

The allowmultiple attribute indicates whether multiple instances of the attribute can exist in the element. If it is setTrueMultiple instances are allowed.False(Default), only one instance is allowed.

In the following code example,MyattributeBy defaultAllowmultipleThe value isFalse, AndYourattributeThe corresponding value isTrue.

//This defaults to AllowMultiple = false.
public class MyAttribute :Attribute
{
}

[AttributeUsage(AllowMultiple = true)]
public class YourAttribute : Attribute
{
}

When multiple instances of these attributes are applied,MyattributeWill generate a compiler error. The following code example showsYourattributeEffective usage andMyattributeIs invalid.

public class MyClass
{
//This produces an error.
//Duplicates are not allowed.
[MyAttribute]
[MyAttribute]
public void MyMethod() {
//...
}

//This is valid.
[YourAttribute]
[YourAttribute]
public void YourMethod(){
//...
}
}

IfAllowmultipleBoth the property and inherited property are setTrueThe class inherited from another class can inherit one attribute and apply another instance of the same attribute to the same subclass. IfAllowmultipleSetFalseAll attribute values in the parent class will overwrite the new instance with the same attribute in the quilt class.

Declare Attribute Class

After attributeusageattribute is applied, you can define the attribute details. The declaration of attribute classes is similar to that of traditional classes, as shown in the following code:

public class MyAttribute : System.Attribute 
{
// . . .
}

This attribute definition describes the following:

  • Attribute classes must be declared as public classes.

  • According to the Conventions, the name of the attribute class is a word.AttributeEnd. Although this is not required, we recommend that you use this convention for readability purposes. You can select whether to include the word attribute when applying the attribute.

  • All attribute classes must directly or indirectlySystem. AttributeInheritance.

  • In Microsoft Visual Basic, all custom attribute classes must have the attributeusageattribute attribute.

Declare Constructors

The methods for initializing attributes using constructors are the same as those for traditional classes. The following code snippet illustrates a typical property constructor. This common constructor uses a parameter and sets its value to be equal to the member variable.

public MyAttribute(bool myvalue)
{
this.myvalue = myvalue;
}

This constructor can be reloaded to adapt to different combinations of values. If a property is defined for a custom property class at the same time, you can use a combination of named parameters and positioning parameters when initializing the property. Generally, all required parameters are defined as positioning parameters, and all optional parameters are defined as named parameters. In this case, attributes cannot be initialized if no required parameter exists. All other parameters are optional. Note that the paramarray parameter should not be used in the constructor of attribute classes in Visual Basic.

The following code example shows how to use the properties of the constructor in the previous example to apply optional and required parameters. It assumes that this attribute has a required Boolean value and an optional string attribute.

//One required (positional) and one optional (named) parameter are applied.
[MyAttribute(false, OptionalParameter = "optional data")]
//One required (positional) parameter is applied.
[MyAttribute(false)]
Declare attributes

If you need to define the name parameter or provide an easy way to return the value stored by the attribute, declare the attribute. Attribute attributes should be declared as public entities with descriptions of the data types to be returned. Defines the variable that will save the property value, andGetMethod andSetMethod Association. The following code example shows how to implement a simple attribute in an attribute.

public bool MyProperty
{
get {return this.myvalue;}
set {this.myvalue = value;}
}
Custom property example

This section describes the previous information and shows how to design a simple attribute to record information about the code snippet author. The attributes in this example store the programmer's name and level, and information about whether the code has been reviewed. In this example, three private variables are used to store the actual values. Each variable is represented by a public attribute that gets and sets these values. Finally, use two required parameters to define the constructor.

[AttributeUsage(AttributeTargets.All)]
public class DeveloperAttribute : System.Attribute
{

//Private fields.
private string name;
private string level;
private bool reviewed;

//This constructor defines two required parameters: name and level.

public DeveloperAttribute(string name,string level)
{
this.name = name;
this.level = level;
this.reviewed = false;
}

//Define Name property.
//This is a read-only attribute.

public virtual string Name
{
get {return name;}
}

//Define Level property.
//This is a read-only attribute.

public virtual string Level
{
get {return level;}
}

//Define Reviewed property.
//This is a read/write attribute.

public virtual bool Reviewed
{
get {return reviewed;}
set {reviewed = value;}
}
}

You can use the full name in one of the following ways:DeveloperattributeOr use the abbreviated nameDeveloperTo apply this property.

[Developer("Joan Smith", "1")]
[Developer("Joan Smith", "1", Reviewed = true)]

The first example shows only the attributes of the mandatory name parameter application, while the second example shows the attributes of the mandatory and optional parameters application.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.