. Net Reflection Reflection Technology

Source: Internet
Author: User

Here, write a personal pair. NET down-reflection technology understanding:

The first part: personal speaking reflex

The reflection mechanism is a mechanism by which the runtime gets the members of the class (type Object) and the dynamic call object.

A. You can obtain member information about loaded assemblies and the types that are defined in them, such as classes, interfaces, and value types;

B. You can use reflection to create objects of the specified class at run time, and to invoke and access members of those objects.

This dynamic acquisition of information and the ability to dynamically invoke the object's methods is called the reflection mechanism.

For example, a Mylyfeng class is defined under Myreflect.ui:

public class Mylyfeng
{
No parameter constructor

Parametric constructors
Public Mylyfeng (string name)
{
THIS.name = name;
}
Private fields
private int beautynum;

public int Beautynum
{
get {return beautynum;}
set {beautynum = value;}
}

private string name;

public string Name
{
get {return name;}
set {name = value;}
}


Non-parametric public method with return value
public string Sayname ()
{
Logic
return null;
}
No parameter no return value private method
private void Sleep ()
{
Logic
}
No return value with parameter
public void SayHello (string name)
{
Logic
}
There are parameters with return values
public string Returnparam (string param)
{
return param;
}
}

1. In general, if you want to get an instance object of the Mylyfeng class, you only need one code:

Mylyfeng Lyf = new Mylyfeng () {beautynum=100};
Mylyfeng lyf2 = new Mylyfeng ("My");

In addition to using the new method above, you can use reflection technology to manipulate the Mylyfeng class.

2. Local dynamic creation

Type type=typeof (Mylyfeng);//local access to Mylyfeng class
No parameter constructor
Object Obj=activator.createinstance (type);
Parametric constructors
ConstructorInfo c= type. GetConstructor (new Type[]{typeof (String)});//constructor argument type
C.invoke (new object[] {"Name"});//argument
of public

Field operations
FieldInfo field= type. GetField ("name");
Field. GetValue (obj);//obj.field
Field. SetValue (obj, "Lyfeng");
Property manipulation
PropertyInfo Property =type. GetProperty ("Beautynum");
Property. GetValue (obj, null);//obj. Beautynum
Property. SetValue (obj, 101,null);

Privately owned
Field operations
fieldinfo[] Fields =type. GetFields (BindingFlags.NonPublic);
foreach (FieldInfo item in fields)
{

}
Property manipulation
propertyinfo[] Propertys = type. GetProperties (bindingflags.nonpublic| BindingFlags.Instance);
foreach (PropertyInfo item in Propertys)
{

}
Method action
No parameter no return value
MethodInfo Method=type. GetMethod ("Sleep");
Method. Invoke (obj, null);
No return value with parameter
MethodInfo method1 = type. GetMethod ("SayHello");
Method1. Invoke (obj, new object[] {"Name"});
No parameter has a return value
MethodInfo Method2=type. GetMethod ("Sayname");
Object Returnvalue=method2. Invoke (Obj,null);
With parameter and return value
MethodInfo Method3=type. GetMethod ("Returnparam");
Object returnvalue=method3. Invoke (obj,new object[]{"param"});
Interface operation
Determines whether the current type implements the Iharry interface
typeof (Iharry). IsAssignableFrom (type);

These are some of the more commonly used examples of comparisons, but in actual development we may not have direct access to the Mylyfeng, so we need to make a little bit of change, the code is as follows:

3. Offsite Dynamic Creation

Suppose there is a Francis class in another class library Ifrancis, which cannot be accessed under Myreflection.ui, we just need to generate the IFrancis.dll (or copy one to Myreflection.ui to bin).

Then use reflection to get the instance object:

String path=appdomain.currentdomain.basedirectory;
Assembly-Assembly.LoadFrom (path + "IFrancis.dll");
Type ftype=. GetType ("Ifrancis.francis");
Object Fobj=activator.createinstance (ftype);
Residual empathy

Part II: Personal use reflex

Dynamic splicing of SQL statements using reflection technology

Insert Example 1:

int beautynum = 102;
String name = "Name";

System.Text.StringBuilder sb = new StringBuilder ()

Assembly-Assembly.LoadFrom (AppDomain.CurrentDomain.BaseDirectory + "IFrancis.dll");
Type type =. GetType ("Ifrancis.francis");
String tableName = type. Name;

Sb. AppendFormat ("Insert into {0} (", tableName);
propertyinfo[] Propertys = type. GetProperties ();
foreach (PropertyInfo item in Propertys)
{
Sb. Append (item. Name + ",");
}
Remove comma
Sb. Remove (sb.) Length-1, 1);
Sb. Append (") VALUES (" + Beautynum + ", '" + name + "')");
Note: This is done based on the properties of the IFrancis.dll assembly to generate the SQL statement, in general, I will use the other one, according to the model entity object as the basis:
Insert Example 2:

Mfrancis model = new Mfrancis () {beautynum = 103, name = "Name"};
string where = "where ...";

System.Text.StringBuilder updatesb = new StringBuilder ();

Type type=typeof (MFRANCIS);

String Tablename=type. Name;

Sb. AppendFormat ("insert into {0} (", tableName);
Propertyinfo[] pi= typeof (Mfrancis). GetProperties ();
list<sqlparameter> list2 = new list<sqlparameter> ();
for (int i = 0; i < PI. Length; i++)
{
Sb. Append (Pi[i]. Name+ ",");
}
Sb. Remove (sb.) length-1,1);
Sb. Append (") VALUES (");
for (int i = 0; i < PI. Length; i++)
{
Sb. Append ("@" +pi[i]. Name+ ",");
SqlParameter p = new SqlParameter ("@" +pi[i]. Name,pi[i]. GetValue (Model,null));
List2. ADD (P);
}
Sb. Remove (sb.) length-1,1);

Update Example:

System.Text.StringBuilder updatesb = new StringBuilder ();

propertyinfo[] pi = typeof (Mfrancis). GetProperties ();//model

list<sqlparameter> list = new list<sqlparameter> ();
Updatesb. AppendFormat ("Update {0} set", TableName);


for (int i = 0; i < pi. Length; i++)
{
Updatesb. AppendFormat (Pi[i]. Name + "[email protected]" + pi[i]. Name + ",");
SqlParameter PS = new SqlParameter ("@" + pi[i]. Name, Pi[i]. GetValue (model, NULL));//class. Property name
List. ADD (PS);
}
Updatesb. Remove (Updatesb. Length-1, 1);
if (string. IsNullOrEmpty (where))
{
Updatesb. Append (where);
}
The UPDATE and INSERT statements here are not complete, because there is actually a where condition that needs to be stitched into a complete SQL based on the Primkey primary key, and the validation of the legitimacy of the model entity object;

. Net Reflection Reflection Technology

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.