"Reading notes" C # Advanced Programming 15th Chapter Reflection

Source: Internet
Author: User

(i) Process and review code during operation

Custom attributes allow you to associate custom metadata with program elements. Reflection is a common term that describes the function of checking and handling program elements while running. For example, reflection allows tasks to complete:

    • Member of enum type
    • Instantiating a new object
    • Members of the Execution object
    • Finding information about an assembly
    • Check for custom attributes that apply to some type
    • Creating and compiling new assemblies

(ii) Custom features

When you use reflection to make custom attributes very powerful, the code can read the metadata and use them to make decisions during run time.

1. Write Custom Features

Define a fieldname attribute:

false false )]publicclass  fieldnameattribute:attribute{    privatestring  name;      Public Fieldnameattribute (string  name)    {        this. Name = name;    }} 

(1) AttributeUsage characteristics

The attribute class itself is marked with an attribute--system.attributeusage attribute. AttributeUsage The first parameter identifies a custom attribute that can be applied to a program element of those types, whose type is enum type Attrubutetargets.

When there are more than 1 application types, you can connect using the OR operator:

false false )]
The AllowMultiple property is used to specify whether the attribute can be applied more than once to the same item, and when set to False, the following encoding will error:
[FieldName (" my Property 1")][fieldname (" my Properties 2")]  publicintgetset; }
The inherited property is used to indicate the class that uses the attribute or whether a class member can be inherited by a derived class or overridden member. 

(2) specifying characteristic parameters

The compiler examines the arguments passed to the attribute and looks for the constructor with those parameters in the attribute. Half provides only one constructor, using properties to define any other optional parameters.

(3) Optional parameters for the specified attribute

Another syntax that can add optional parameters to an attribute. This syntax specifies the name and value of an optional parameter, which works through a public property or field in an attribute class. For example, the AllowMultiple and inherited used by the AttributeUsage attribute in the code above are the syntax used.

(iii) Reflection

Information about any data type can be accessed through the System.Type class. The System.Reflection.Assembly class can be used to access information about a given assembly, or to load the assembly into a program.

1, System.Type class

The type has derived classes that correspond to each data type. Gets a type reference that specifies any given type in 3 common ways:

Using the C # typeof operator:

typeof (double);

Use The GetType () method (all classes inherit this method from System.Object):

Double 10.0  = D.gettype ();

Use static method GetType () for the type class:

Type type = Type.GetType ("system.double");

(1) Properties of type

1 class Program2 {3     Static voidMain (string[] args)4     {5Type Inttype =typeof(int);6Console.WriteLine ("type name of the current type:"+inttype.name);7Console.WriteLine ("type fully qualified name of the current type:"+inttype.fullname);8Console.WriteLine ("Namespace name of the current type:"+inttype.namespace);9Console.WriteLine ("direct base class name for the current type:"+inttype.basetype);TenConsole.WriteLine ("of the current type. NET runtime map to the type:"+inttype.underlyingsystemtype); OneConsole.WriteLine ("is an array of:"+Inttype.isarray); AConsole.WriteLine ("is a value type:"+inttype.isvaluetype); -     } - } the  Public classMyBaseClass {} -  Public classMyclass:mybaseclass {}

Run the above code with the following results:

There are many isxxx to determine whether it is a certain type.

(2) method

Most methods of the System.Type class are used to obtain member information for the corresponding data type: Constructors, properties, methods, and events. The suffix plus ' s ' means getting all the member-related information for the current data type, without adding information about only one member of the data type.

typeof (int); var method = Inttype.getmethod ("GetHashCode"); var methods = inttype.getmethods (); foreach (var in methods) {}

The System.Type class also contains GetConstructor () methods and GetConstructors ().

2, Assembly class

The Assembly class is defined in the System.Reflection namespace, which allows access to the metadata of a given assembly, and it also contains methods that can load and execute an assembly (assuming that the assembly is executable). You can use static member Assembly.Load () or Assembly.LoadFrom ().

Load using Load ():

Assembly assembly1 = Assembly.Load (" assembly name ");

Load with LoadFrom ():

Assembly assembly2 = Assembly.LoadFrom (" assembly actual path ");

After the assembly is loaded, it can be queried using its various properties:

string name = Assembly1. FullName;

(1) Get more information about the types defined in the assembly

One of the functions of the Assembly class is that it can obtain details of all types defined in the corresponding assembly, as long as the Assembly.gettypes () method is called, you can return an array of System.Type references that contain details of all types.

Type[] Typearray = assembly. GetTypes ();

(2) Detailed information on the characteristics obtained

If you want to determine what custom attributes the assembly is associated with as a whole, you need to call a static method GetCustomAttributes () of the attribute class.

attribute[] Definedattributes = attribute.getcustomattributes (assembly);

"Reading notes" C # Advanced Programming 15th Chapter Reflection

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.