C # Features

Source: Internet
Author: User

What is characteristic, my own understanding is:

An attribute is a language structure that allows us to add metadata to an assembly. It is a special class for saving program structure information. Features have 2 basic concepts: "Target", "consumer", take the special DebuggerStepThrough, the compiler is the consumer, when it encountered by this feature registered mothed, Will not enter this mothed execution (when the breakpoint) is directly get the results of this methed operation, and the second method is the target. All in all, the language structure in which the attribute is applied is called "target"; it is called "consumer" that is designed to acquire and use this attribute.

Explained below. NET comes with some of the more famous features

1,obsolete: Prompt Method obsolete

using system;using system.collections.generic;using system.linq;using system.text; namespace atrributetest.com{    /// <summary>    ///   For testing obsolete properties     ///  targets:method    ///  consumer  :  IDE    /// </summary>    public sealed  Class obsoletetest    {        [obsolete (" This method is obsolete, please use the Mynewmethod method ", false)]        public void  MYOLDMETHD ()         {             console.writeline ("This is an outdated method");        }         public void mynewmethod ()          {             console.writeline ("This is a new method");         }    }}

Test:

650) this.width=650; "title=" 01.png "alt=" wkiol1jg5iidyvq6aabrep3jcua875.png-wh_50 "src=" https://s4.51cto.com/ Wyfs02/m01/8f/7c/wkiol1jg5iidyvq6aabrep3jcua875.png-wh_500x0-wm_3-wmp_4-s_520375797.png "/>

As you can see, when the IDE jumps out of the way, it will automatically line up on the method with the "Obsolete" flag (which means it is deprecated), and in the Obsolete constructor, I hint "This method is obsolete, use the Mynewmethod method" and only show it in the IDE's hints. For the second parameter (Boolean) of obsolete, it is "not available." If true, when the Myoldmethd method is used, the compilation will give an error and vice versa (false), but it is not advocated.


2,conditional: Canceling any call to method

I think this is not a good compile parameter. I'll put the test code in, and I'll explain.

1, there is a method in which "Mytestmethod" is modified by the conditional property

Using system;using system.collections.generic;using system.diagnostics;using system.linq;using System.Text;  namespace atrributetest.com{//<summary>///For testing condition features//target: Method//Consumer: IDE (will affect compilation)// </summary> public sealed class Conditionaltest {[Conditional ("Istest")] public void Mytestmeth        OD () {Console.WriteLine ("This is my test method, please comment out after the official launch"); }    }}

This method is called at 2

①:

using system;using system.collections.generic;using system.linq;using system.text; namespace atrributetest.com{    /// <summary>    ///   For testing obsolete properties     ///  targets:method    ///  consumer  :  IDE    /// </summary>    public sealed  Class obsoletetest    {        [obsolete (" This method is obsolete, please use the Mynewmethod method ", false)]        public void  MYOLDMETHD ()         {             console.writeline ("This is an outdated method");        }         public void mynewmethod ()          {             console.writeline ("This is a new method");             conditionaltest conttest = new conditionaltest () ;             conttest.mytestmethod ();         }    }}

②:main function

#define  IsTestusing System;using System.Collections.Generic;using System.Linq;using  system.text;using atrributetest.com;namespace atrributetest{    public  Class program    {        static void  main (String[] args)         {             console.writeline ("Obsoletetest ........ .............            obsoletetest obstest = new  obsoletetest ();             Obstest.mynewmethod ();                conditionaltest contest =  New conditionaltest ();             Contest.mytestmethod ();             console.readkey ();         }    }}

In program I have defined a macro istest, so mytestmethod can be executed in the main function of this class. However, this macro is not defined in Obsoletetest, so mytestmethod in this class of methods Mynewmethod will not be executed. This is worth noting. You've actually already given the hint in the IDE:

In the program class that has registered the Istest macro, such as:

650) this.width=650; "title=" 02.png "alt=" wkiol1jg8vhrbgsgaacpflfk6zw151.png-wh_50 "src=" https://s4.51cto.com/ Wyfs02/m01/8f/7c/wkiol1jg8vhrbgsgaacpflfk6zw151.png-wh_500x0-wm_3-wmp_4-s_1673394904.png "/>

In the Obsoletetest class that has not registered a macro Istest macro, such as:

650) this.width=650; "title=" 03.png "alt=" wkiom1jg88viwsjoaabqn268-6o200.png-wh_50 "src=" https://s2.51cto.com/ Wyfs02/m00/8f/7e/wkiom1jg88viwsjoaabqn268-6o200.png-wh_500x0-wm_3-wmp_4-s_1133675566.png "/>

It is important to note that the ① macro must be preceded by all using, and the ② macro should be defined the same as the parameter following [Conditional ("Istest")], but not "" (quotation marks)

But if this method of the whole project can/cannot be called, adding/deleting Macros in class alone will be exhausting. Here I have a good way "pre-processing instructions" In my blog "C # preprocessing directives of the global design", but there is one other drawback of this feature:

All references (calls) to this method will not be compiled, but the place where it is defined will be compiled. Suggest or use the #if/#endif


Custom attributes: (note three points)

One: Need to inherit the attribute class

Two: Need to attribute word as suffix name

Three: It is better to affirm that the sealed, need to affirm this characteristic consumption

OK, now to the whole demo, now step by step implementation

① establishes the first custom attribute, such as

650) this.width=650; "title=" 04.png "alt=" wkiol1jhbjicp1muaabga-pfk2w116.png-wh_50 "src=" https://s4.51cto.com/ Wyfs02/m02/8f/7c/wkiol1jhbjicp1muaabga-pfk2w116.png-wh_500x0-wm_3-wmp_4-s_731309138.png "/>

② Complete code:

using system;using system.collections.generic;using system.linq;using system.text; namespace atrributetest.com{    /// <summary>    ///   Customizing an attribute     /// </summary>    [attributeusage ( AttributeTargets.Class)]//indicates that this feature can be applied to those program structures     public  sealed class  mytestattribute : attribute    {         private string des;        public int id {  get; set; }        public mytestattribute (String   @des)         {             this.des = des;        }     }}

③ using custom Attributes

Note: Use reflection to get attribute information

650) this.width=650; "title=" 05.png "alt=" wkiol1jhb7sgbb0waab1as250pg300.png-wh_50 "src=" https://s5.51cto.com/ Wyfs02/m00/8f/7c/wkiol1jhb7sgbb0waab1as250pg300.png-wh_500x0-wm_3-wmp_4-s_1142905651.png "/>

using system;using atrributetest.com;namespace atrributetest{        [mytest ("My first feature", id = 1)]    public class program     {        private static void main ( String[] args)         {             Type  @ty  = typeof  (program);             object[] arr = ty. GetCustomAttributes (false);//whether to search for attributes on parent class              MyTestAttribute my = arr[0] as MyTestAttribute;             console.writeline ("des : {0} of the attribute Class"  , my.des);            &nbsp Console.WriteLine (ID number  : {0} for the attribute class  ,my. ID);             console.readkey ();         }    }}

This article is from the "Better_power_wisdom" blog, make sure to keep this source http://aonaufly.blog.51cto.com/3554853/1912608

C # Features

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.