C #-method attribute and reflection

Source: Internet
Author: User
In C #, feature attribute is used in many places. It can be used to describe the type or method, thus granting them some additional functions or features. In fact, when you open Visual Studio and create a Windows Forms Application Program In the default program. CS file, the main function is marked with feature attributes.

[Stathread]
Static   Void Main ()
{
}

A feature attribute is a group of classes that inherit from the attribute. It is usually used to modify the type or method and is enclosed in square brackets before the type or method definition. For example, we can add a feature attribute to the class so that it can be serialized as XML:

Public   Class Movie
{
[Xmlelement ( " Moviename " )]
Public   String Title
{ Get ; Set ;}

[xmlelement ( " movierating " )]
Public float rating
{ Get ; set ;}

[Xmlelement ("Moviereleasedate")]
PublicDatetime releasedate
{Get;Set;}
}

As shown in the precedingCodeFragment and feature attributes allow receiving parameters, depending on what type of feature property you use. Of course, we can also customize feature attribute classes in. net, but the premise is that the custom class must inherit the custom attribute class. The following is an example:

Class Mytoken: attribute
{
Public   String Displayname { Get ; Set ;}

PublicMytoken (StringDN)
{Displayname=DN ;}
}

Then, we use the custom feature Attribute Class in the Code:

Public   Static   Class Operations
{
[Mytoken ( " Operation 1 " )]
Public   Static   Void Operation1 ()
{
System. Windows. Forms. MessageBox. Show ( " Hey, I'm operation 1! " );
}

[Mytoken ("Operation 2")]
Public Static VoidOperation2 ()
{
System. Windows. Forms. MessageBox. Show ("Hey, I'm operation 2!");
}
}

So what is the significance of using custom feature attributes before a method? Let's take a look at an actual example. We use reflection to find out all the methods marked as our custom feature attributes.

Using System;
Using System. Collections. Generic;
Using System. componentmodel;
Using System. Data;
Using System. drawing;
Using System. LINQ;
Using System. text;
Using System. Windows. forms;
Using System. reflection;

namespace windowsformsapplication1
{< br> Public partial class form1: form
{< br> Public form1 ()
{< br> initializecomponent ();
populatecombox ();
}

Private VoidPopulatecombox ()
{
Methodinfo [] Methods= Typeof(Operations). getmethods ();

Mytoken token =   Null ;
List < Keyvaluepair < String, methodinfo > Items =   New List < Keyvaluepair < String , Methodinfo > ();

Foreach (Methodinfo Method In Methods)
{
Token = Attribute. getcustomattribute (method, Typeof (Mytoken ), False ) As Mytoken;
If (Token =   Null )
{
Continue ;
}

Items. Add (NewKeyvaluepair<String, methodinfo>(Token. displayname, method ));
}

This . Combobox1.datasource = Items;
This . Combobox1.displaymember =   " Key " ;
This . Combobox1.valuemember =   " Value " ;
}

Private   Void Button#click ( Object Sender, eventargs E)
{
If ( This . Combobox1.selectedindex <   0 )
{
Return ;
}

Methodinfo Method =   This . Combobox1.selectedvalue As Methodinfo;
If (Method ! =   Null )
{
Method. Invoke ( Null , Null );
}
}
}

Public class mytoken: attribute
{< br> Public string displayname { Get ; set ;}

PublicMytoken (StringDN)
{Displayname=DN ;}
}

Public   Static   Class Operations
{
[Obsolete]
Public   Static   Void Operation0 ()
{
System. Windows. Forms. MessageBox. Show ( " Hey, I'm operation 0! " );
}

" operation 1 " )]
Public static void operation1 ()
{< br> system. windows. forms. messageBox. show ( " Hey, i'm operation 1! " );
}

" operation 2 " )]
Public static void operation2 ()
{< br> system. windows. forms. messageBox. show ( " Hey, i'm operation 2! " );
}

Public Static VoidOperation3 ()
{
System. Windows. Forms. MessageBox. Show ("Hey, I'm operation 3!");
}
}
}

The above is the complete code of a winform program. There are two controls on the form, one combox and one button. When the program starts, it calls the populatecombox () method to identify all the methods marked as mytoken feature attributes in the operations class through reflection and add them to the set list. There are two points to describe:

1. Use attribute.Getcustomattribute() Method to find all the methods marked as mytoken feature attributes in the methodinfo [] array. Note the parameter format of the getcustomattribute () method. Typeof (Operations). getmethods () is used to return all public access-level methods in operations.

2. The set items is defined as a list generic type. The list generic type is specified as a name-value pair. In fact, you can also use any set type with name-value pairs, such as hashtable.

When you click the button, the program uses the combox. selectedvalue attribute to find the name of the currently selected method, and then runs it using the invoke () method. The following shows the effect of program execution.

 

You should note that there are only two items in combox: operation1 and operation2. However, we can see that there are four static methods defined as public access in the operations class. Why does reflection only find two methods? This is because only the method defined as mytoken feature attribute is defined in reflection. Method operation0 is defined as feature attribute obsolete (this feature attribute is used to identify that the method has expired and is no longer used, you should be in some early stages. the type or method released in the. NET version has seen this identifier, or has seen it in the smart prompts of the Code.) instead of the mytoken, method operation3 does not contain feature attributes. The biggest benefit of reflection is that it can dynamically load the Assembly, obtain the types in the Assembly, and the attributes and methods in the type, and execute them. In the above example, if you want to add a new operation method and make it appear in the combox and be executed, you only need to do one thing, that is, add a method in the operations class and mark it as the mytoken feature attribute, and add the code you want to execute.

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.