Introduction to. Net built-in feature Attribute,. net feature attribute

Source: Internet
Author: User
Tags sendmsg

Introduction to. Net built-in feature Attribute,. net feature attribute

Feature Attribute Overview

Attribute is a special type that can be loaded to an assembly or assembly. These types include modules, classes, interfaces, structures, constructors, methods, and fields, the type of the loaded feature is called the target of the feature. This is distinguished from Property, so it is called Attribute ). A feature is a mechanism for adding metadata to an assembly. It can provide instructions for the compiler or describe the data. For example, the Remoting technique (mainly used for object communication between application domains) learned earlier has the Serializable feature when it references objects between application domains. The following describes how to use the ObsoleteAttribute feature learning feature.

System. ObsoleteAttribute instance

We have an old method SendMsg () which is overloaded by function and efficiency optimization. We need to add the Obsolete feature to the original method to inform the compiler that this method is outdated, then, when the compiler finds that a method marked with this feature is used in a program, the following warning message is displayed:

The test code is as follows:

Using System; namespace AttributeTest {// <summary> // Information Entity class // </summary> public class Message {// specific implementation here} // <summary>/ // information operation class /// </summary> public class MessageOperation {[Obsolete ("use the new SendMsg (Message msg) overload method ")] public static void SendMsg () {Console. writeLine ("this is the old SendMsg method");} public static void SendMsg (Message msg) {Console. writeLine ("this is the new SendMsg method");} class Program {static void Main (string [] args) {// use the old method SendMsg () MessageOperation. sendMsg (); // use the new method SendMsg (Message msg) MessageOperation. sendMsg (new Message ());}}}

In this way, the developer will see the warning "Please use the new SendMsg (Message msg) overload method" during compilation and runtime, and then they will know that the new SendMsg (Message msg) should be selected) overload method. The above example shows the method used by the feature: first, a pair of square brackets "[]" followed by the feature name in the left square brackets, such as Obsolete. Then there is a parentheses "()". In this parentheses, you can not only input the constructor parameters, but also assign values to the properties of the feature. In the Obsolete example, only parameters of the constructor are passed. A constructor is also called a location parameter (the input sequence must be consistent with that declared by the constructor). An attribute parameter is also called a naming parameter.

Next, we will further learn the features through custom features.

Custom features

Suppose we have such a requirement: to create or update a class file, we need to explain when the class was created and who was updated later, do you want to add comments to the class as follows:

In this way, manual addition can be recorded, but it is obviously not suitable to view all types of update records. With such a suspense, let's take a look at the specific definition of the Obsolete feature as follows:

Using System. Runtime. InteropServices; namespace System {// Summary: // mark the program elements that are no longer in use. This class cannot be inherited. [Serializable] [AttributeUsage (AttributeTargets. class | AttributeTargets. struct | AttributeTargets. enum | AttributeTargets. constructor | AttributeTargets. method | AttributeTargets. property | AttributeTargets. field | AttributeTargets. event | AttributeTargets. interface | AttributeTargets. delegate, Inherited = false)] [ComVisible (true)] public sealed class ObsoleteAttribute: Attribute {// Abstract: // use The default attribute initializes a new instance of the System. ObsoleteAttribute class. Public ObsoleteAttribute (); // Abstract: // use the specified work und to initialize a new instance of the System. ObsoleteAttribute class. //// Parameter: // message: // text string that describes the optional work und. Public ObsoleteAttribute (string message); // Abstract: // use the work und message and Boolean value to initialize the System. the new instance of the ObsoleteAttribute class. This Boolean value indicates whether to treat obsolete elements as errors. //// Parameter: // message: // text string that describes the optional work und. //// Error: // indicates whether to treat obsolete elements as incorrect boolean values. Public ObsoleteAttribute (string message, bool error); // Abstract: // obtain a Boolean value indicating whether the compiler treats obsolete program elements as incorrect. //// Return result: // If the obsolete element is regarded as an error, true is returned; otherwise, false is returned. The default value is false. Public bool IsError {get;} /// Abstract: // obtain the work und message, including description of the optional program elements. //// Return result: // The variable Text string. Public string Message {get ;}}}

We can see that the Obsolete feature inherits the Attribute (required for this feature) during definition, and uses the Serializable, ComVisible, and AttributeUsage attributes. The Serializable attribute indicates that the type supports serialization; The ComVisible attribute is true, indicating that the managed type (public type) is visible to COM; When AttributeUsage defines your own feature class, you can place AttributeUsageAttribute on the feature class to control the usage of the feature class.

Based on the above learning and the above requirements, we customize a RecordAttribute feature, and the Implementation Code is as follows:

// This feature can be used for methods and classes and can be repeatedly used for special offers to a type [AttributeUsage (AttributeTargets. class | AttributeTargets. method, AllowMultiple = true)] public class recordattriple: Attribute {private string _ recordType; // record type: update or create private string _ author; // author private string _ date; // date private string _ comment; // remarks // constructor public RecordAttribute (string recordType, string author, string date) {_ recordType = recordType; _ author = author; _ date = date;} // for location parameters, only the get accessors public string RecordType {get {return _ recordType ;}} are provided ;}} public string Author {get {return _ author ;}} public string Date {get {return _ date ;}// construct an attribute, in the feature, it is also called the named parameter public string Comment {get; set ;}}

The modified or updated features of the record class have been created. The following is an example:

[Record ("Update", "", "2014.8.3", Comment = "add ToString () method")] [Record ("Update", "", "2014.8.3")] [Record ("CREATE", "", "2014.8.2")] public class Message {// specific implementation of public override string ToString () {return "added the ToString () method ";}}
In this way, the above requirements are successfully met. The Record attribute added to the Message class is actually added to the Assembly as metadata.
What is the purpose of the Attribute in C?

For the first question, refer to my other answer: zhidao.baidu.com/question/463506213.html.
The second question is yes. For example, I will add it to you tomorrow morning.

C # How to understand attributes

Hello, please distinguish between Attribute and Property ).
Attribute is the data field encapsulated in the class in object-oriented thinking.

The C # feature can be applied before various types and members. The main purpose of a feature is self-description. In addition, because the features can be customized by yourself, rather than just the ready-made features provided by. NET, it brings great flexibility and convenience to C # program development. In addition, features are also class. Unlike other classes, features must be inherited from the System. Attribute Class. Otherwise, how does the compiler know who is a feature and who is a common class. When the compiler detects that a class is a feature, it will recognize that the information is stored in the metadata. That's all. The Compiler does not care about what the feature says, the feature does not play any role in the compiler.

Related Article

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.