C # comprehensive secrets-the mysteries of reflection

Source: Internet
Author: User

Reflection is a process of discovering and running an assembly. through reflection, you can obtain information inside the *. exe or *. dll assembly. Reflection allows you to view the interfaces, classes, methods, fields, attributes, and features of an assembly. The System. Reflection namespace contains multiple frequently-used classes for Reflection. The following table lists the frequently-used classes.

 

Type Function
Assembly This class can be used to load and manipulate an assembly and obtain internal information of the Assembly.
EventInfo This class stores the specified event information
FieldInfo This class stores the given field information
MethodInfo This class saves the given method information
MemberInfo This class is a base class that defines multiple public behaviors of EventInfo, FieldInfo, MethodInfo, and PropertyInfo.
Module This class allows you to access the given modules in multiple assemblies.
ParameterInfo This class saves the given parameter information
PropertyInfo This class saves the given property information

 

 

1. System. Reflection. Assembly class

You can use Assembly to dynamically Load an Assembly and view its internal information. The most common method is Load.

Assembly assembly = Assembly. Load ("MyAssembly ");

The object CreateInstance (string) method of Assembly can be used to create an object. parameter 0 is the class name.

 

 

Ii. System. Type class

Type is the most commonly used class. You can obtain the internal information of a class through Type, or create an object through reflection. Generally, there are three common methods to obtain the Type object.

  1. Use typeof () to obtain the Type object

    Type type = typeof (Example );

  2. Use System. Object. GetType () to obtain the Type Object.

    Example example = new Example ();

    Type type = example. GetType ();

  3. Use System. Type. GetType () to obtain the Type object.

    Type type = Type. GetType ("MyAssembly. Example", false, true );

    Note that parameter 0 is the class name. Parameter 1 indicates whether an exception is thrown if the corresponding class cannot be found, and parameter 1 indicates whether the class name is case sensitive.

Example:

We usually use reflection and Activator to create objects.

Assembly assembly = Assembly. Load ("MyAssembly ");

Type type = assembly. GetType ("Example ");

Object obj = Activator. CreateInstance (type );

 

Iii. Reflection Method

1. You can use System. Reflection. MethodInfo to find the methods in the class.

Code:

Type type = typeof (Example );

MethodInfo [] listMethodInfo = type. GetMethods ();

Foreach (MethodInfo methodInfo in listMethodInfo)

Cosole. WriteLine ("Method name is" + methodInfo. Name );

2. We can also execute the methods in the class through the reflection method.

Code:

Assembly assembly = Assembly. Load ("MyAssembly ");

Type type = assembly. GetType ("Example ");

Object obj = Activator. CreateInstance (type );

MethodInfo methodInfo = type. GetMethod ("Hello World"); // obtain the MethodInfo object based on the method name

MethodInfo. Invoke (obj, null); // parameter 1 is of the object [] type, representing the corresponding parameter of the Hello World method. If the input value is null, it indicates no parameter.

 

 

Iv. Reflection attributes

1. You can use System. Reflection. PropertyInfo to find the attributes in the class.

Common methods include GetValue (object, object []) to get the attribute value and SetValue (object, object, object []) to set the attribute value.

Code:

Type type = typeof (Example );

PropertyInfo [] listPropertyInfo = type. GetProperties ();

Foreach (PropertyInfo propertyInfo in listPropertyInfo)

Cosole. WriteLine ("Property name is" + propertyInfo. Name );

2. You can also set or obtain the attribute value of an object using the following methods:

Code:

Assembly assembly = Assembly. Load ("MyAssembly ");

Type type = assembly. GetType ("Example ");

Object obj = Activator. CreateInstance (type );

PropertyInfo propertyInfo = obj. GetProperty ("Name"); // get the Name property object

Var name = propertyInfo. GetValue (obj, null); // get the value of the Name attribute

PropertyInfo propertyInfo2 = obj. GetProperty ("Age"); // get the Age property object

PropertyInfo. SetValue (obj, 34, null); // set the Age attribute to 34

 

 

V. Reflection Fields

You can use System. Reflection. FieldInfo to find the fields in the class.

It includes two common methods: SetValue (object, object) and GetValue (object). Because the usage method is very similar to the reflection attribute, we will not introduce it more here.

(Omitted)

 

 

Vi. reflection features

The GetCustomAttributes (Type, bool) of System. Reflection. MemberInfo can reflect the features in a class. The following example can reflect all the features of a class.

Code:

Type type = typeof ("Example ");

Object [] typeAttributes = type. GetCustomAttributes (false); // obtain the features of the Example class

Foreach (object attribute in typeAttributes)

Console. WriteLine ("Attributes description is" + attribute. ToString ());

The following Example shows all the features of the Name attribute of the Example class.

Code:

Public class Example

{

[DataMemberAttribute]

Publics string Name

{Get; set ;}

..................

}

Type type = typeof (Example );
PropertyInfo propertyInfo = type. GetProperty ("Name"); // obtain the Name attribute of the Example class
Foreach (object attribute in propertyInfo. GetCustomAttributes (false) // traverses all features of the Name attribute
Console. WriteLine ("Property attribute:" + attribute. ToString ());

 

Www.2cto.com

VII. Common instances

Although reflection has many mysteries, it takes a lot of performance to use reflection to generate objects. You must understand the characteristics of reflection and use it in a proper place. The most common example is to use the single mode and reflection together. When BLL calls the DAL, it generates the DAL instance through a reflection factory.

.

Namespace Project. Common
{
Public class Factory
{
// Record the dal object
Private static Hashtable dals;
// Use assemblyString to record the full name of the DAL assembly
Private static string assemblyString = ConfigurationManager. etettings ["LinqDAL"];
Private static Assembly assembly;

Static Factory ()
{
Dals = new Hashtable ();
Assembly = Assembly. Load (assemblyString );
}

Private static object CreateInstance (string typeName)
{
// Save the reflection object to the dals set when loading for the first time
If (! Dals. ContainsKey (typeName ))
{
// Create a reflection object
Object object1 = assembly. CreateInstance (typeName );

If (object1 = null)
Throw new Exception ("failed to create this object ");
// Add the object to the dals set
Dals ["typeName"] = object1;
}
Return dals ["typeName"];
}

Public static IExampleDAL CreateExampleDAL ()
{
Return (IExampleDAL) CreateInstance (assemblyString + ". ExampleDAL ");
}
}

Class Program
{
// Generate an object using the factory Mode
Static void Main (string [] args)
{
IExampleDAL iExampleDAL = Factory. CreateExampleDAL ();
.................
Console. ReadKey ();
}
}
}

Namespace Project. IDAL
{
Public interface IExampleDAL
{
/// <Summary>
/// Insert the Example row. If the insertion is successful, the number of new Example rows is returned.
/// </Summary>
/// <Param name = "example"> Example object </param>
/// <Returns> the number of new Example rows is returned. The default value is-1. </returns>
Int AddExample (Example example );

/// <Summary>
/// Update the Example table. If the Update succeeds, the number of data records that have been updated is returned. If the Update fails,-1 is returned.
/// </Summary>
/// <Param name = "example"> Example object </param>
/// <Returns> the number of updated data records is returned after successful Update, and-1 is returned if a failure occurs. </returns>
Int UpdateExample (Example example );

/// <Summary>
/// Delete the row whose ID is equal to exampleID In the Example table. The number of deleted rows is returned.
/// </Summary>
/// <Param name = "exampleID"> ID value of the Example object </param>
/// <Returns> return the number of deleted rows </returns>
Int DeleteExample (int exampleID );

/// <Summary>
/// Obtain all rows in the Example table
/// </Summary>
/// <Returns> return all Example objects in the Example Table </returns>
IList <Example> GetList ();

/// <Summary>
/// Obtain the corresponding Example object based on the ID
/// </Summary>
/// <Param name = "id"> </param>
/// <Returns> </returns>
Example GetExampleByID (int id );
}
}

Namespace Project. DAL
{
Public class ExampleDAL: IExampleDAL
{
Public int AddExample (Example example)
{
// Implement the AddExample Method
...........................
}
..................................
..................................
}
}

 

 

 

The above only introduces the basic usage of reflection. Of course, reflection has many other purposes. The following articles will introduce them one by one.

 

Author: Dust and waves

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.