Reflection in C #
Reflection objects are used to obtain type information at runtime. These classes provide access to the program's metadata running in the System.Reflection namespace in C #.
In C # Namespace System.Reflection contains classes that allow you to obtain information about the application and to dynamically add types, values, and objects to the Application.
The application of Reflection
Reflection has the following applications:
- Allows viewing attribute information at runtime.
- Allows checking different types in an assembly and initializing these types.
- Allow Late Binding to methods and properties.
- Lets create new styles at runtime and then perform some tasks using these types.
See Metadata in C #
We mentioned in the previous article that using Reflection, you can view attribute information.
The MemberInfo object of the System.Reflection class in C # needs to be initialized to detect the attributes associated with a class. To do this, you define an object of the target class, like:
System . Reflection . MemberInfo info = typeof ( MyClass );
The following example illustrates this: creating 3 classes named HelpAttribute, MyClass, and Tester respectively :
using System ; namespace VdMetadata { [ AttributeUsage ( AttributeTargets . All )] public class HelpAttribute : System . Attribute { public readonly string Url ; public string Topic // Topic la mot name parameter
{ get { return topic ; } set { topic = value ; } } public HelpAttribute ( string url ) // url la mot positional parameter
{ this . Url = url ; } private string topic ; } [ HelpAttribute ( "Thông tin của lớp MyClass" )] class MyClass {
} class Tester { static void Main ( string [] args ) { Console . WriteLine ( "Reflection trong C#" ); Console . WriteLine ( "--------------------------" ); System . Reflection . MemberInfo info = typeof ( MyClass ); object [] attributes = info . GetCustomAttributes ( true ); for ( int i = 0 ; i < attributes . Length ; i ++) { System . Console . WriteLine ( attributes [ i ]); } Console . ReadKey (); } } }
Compiling and running the C # program on you will get the results:
Reflection in C #
--------------------------
VdMetadata.HelpAttribute
For example
In this example, we use the attribute DeBugInfo created in the previous lesson and use Reflection to read the metadata in the Rectangle class.
using System ; using System . Reflection ; namespace QTMCSharp { // BugFix được gán cho lớp và thành viên của nó [ AttributeUsage ( AttributeTargets . Class | AttributeTargets . Constructor | AttributeTargets . Field | AttributeTargets . Method | AttributeTargets . Property , AllowMultiple = true )] public class DeBugInfo : System . Attribute { private int bugNo ; private string developer ; private string lastReview ; public string message ; public DeBugInfo ( int bg , string dev , string d ) { this . bugNo = bg ; this . developer = dev ; this . lastReview = d ; } public int BugNo { get { return bugNo ; } } public string Developer { get { return developer ; } } public string LastReview { get { return lastReview ; } } public string Message { get { return message ; } set { message = value ; } } }
[ DeBugInfo ( 45 , "Nguyễn Huy" , "03/09/2017" , Message = "Kiểu trả về không hợp lệ" )] [ DeBugInfo ( 49 , "Hà Minh" , "09/11/2017" , Message = "Biến chưa được sử dụng" )] class Rectangle { //các biến thành viên protected double dai ; protected double rong ; public Rectangle ( double d , double r ) { dai = d ; rong = r ; } [ DeBugInfo ( 55 , "Nguyễn Huy" , "03/09/2017" , Message = "Kiểu trả về không hợp lệ" ) ] public double tinhS () { return dai * rong ; } [ DeBugInfo ( 56 , "Hà Minh" , "09/11/2017" ) ] public void Display () { Console . WriteLine ( "Chiều dài: {0}" , dai ); Console . WriteLine ( "Chiều rộng: {0}" , rong ); Console . WriteLine ( "Diện tích: {0}" , tinhS ()); } } //Hết lớp Rectangle
class ExecuteRectangle { static void Main ( string [] args ) { Rectangle r = new Rectangle ( 4.5 , 7.5 ); r . Display (); Type type = typeof ( Rectangle ); //lặp qua các thuộc tính của lớp Rectangle. foreach ( Object attributes in type . GetCustomAttributes ( false )) { DeBugInfo dbi = ( DeBugInfo ) attributes ; if ( null != dbi ) { Console . WriteLine ( "Mã lỗi: {0}" , dbi . BugNo ); Console . WriteLine ( "Nhà phát triển: {0}" , dbi . Developer ); Console . WriteLine ( "Xem lần cuối: {0}" , dbi . LastReview ); Console . WriteLine ( "Ghi chú: {0}" , dbi . Message ); } } // lặp qua các thuộc tính của phương thức. foreach ( MethodInfo m in type . GetMethods ()) { foreach ( Attribute a in m . GetCustomAttributes ( true )) { DeBugInfo dbi = ( DeBugInfo ) a ; if ( null != dbi ) { Console . WriteLine ( "Bug no: {0}, for Method: {1}" , dbi . BugNo , m . Name ); Console . WriteLine ( "Developer: {0}" , dbi . Developer ); Console . WriteLine ( "Last Reviewed: {0}" , dbi . LastReview ); Console . WriteLine ( "Remarks: {0}" , dbi . Message ); } } } Console . ReadLine (); } } }
Compiling and running the above C # program will produce the following results:
Length: 4.5
Width: 7.5
Area: 33.75
Error code: 45
Developer: Nguyen Huy
See last time: September 3, 2017
Note: The return type is invalid
Error code: 49
Developer: Ha Minh
Last viewed: November 9, 2017
Note: The variable has not been used
Bug no: 55, for Method: tinhS
Developer: Nguyen Huy
Last Reviewed: September 3, 2017
Remarks: Invalid return type
Bug no: 56, for Method: Display
Developer: Ha Minh
Last Reviewed: November 9, 2017
Remarks:
According to Tutorialspoint
Previous post: Attribute in C #
Next article: Indexer in C #
You should read it
- Download the official iPhone X Reflection ringtone from Apple
- How to use Photoshop CS5 - Part 13: Create a reflection effect from the water
- How to view EXIF data of photos on iPhone, iPad
- How does the two-way mirror in the interrogation rooms work?
- Tips for Photoshop: Create a reflection of the sun
- Pervert found the victim's house by zooming into her eyes through selfie photos on social networks
- How to recover deleted photos with EXIF metadata
- Head element in HTML
May be interested
- Realizing these 12 facts, you will grow fasterif you say life is absolutely beautiful, it is a false statement. because, just as h. jackson brown once said: remember that everyone is afraid of something, loves something and has lost something - remember that anyone you meet is afraid of something, loves something and i have also lost something - you don't know it.
- 25 valuable lessons about life from famous moviesmovies are not just for entertainment. deeply in every cinematic work, there are always valuable lessons about love, human love and life, making viewers every time have a lot of reflection.
- 12 caricatures of real life make you pondermaybe after observing the sarcastic images of real life, it takes a while for you to understand the deep meaning behind that the author wants to convey to each person. here are 12 works by famous artist painter gunduz agayev.
- How to survive when an earthquake occurs?earthquakes often cause very serious consequences. therefore, equipping survival skills when an earthquake occurs is really necessary for everyone. let's refer to offline!
- Pervert found the victim's house by zooming into her eyes through selfie photos on social networksperverted find the address of the victim through the selfie that the girl or posted on social networks by zooming in on things reflected in her eyes - literally!
- 20 paintings satire another aspect of the world we live intry looking through 20 pictures of satirizing a different aspect of the world we live below to see how you understand. it's not that simple!
- 20 meaningful caricatures of the present state of modern societycheck out 20 extremely meaningful and profound cartoon pictures of steve cutts to reflect on the current state of modern technology society in the article below!
- Why are human veins green while blood is red?we all know that human blood is red, but the veins under the skin are green. it is due to the light reflection of the skin, the amount of oxygen in the blood and other factors.
- Can humans avoid bullets flying like in action movies?in action movies, we see scenes of actors avoiding, avoiding a bullet very easily with cinematic techniques. so, in real life, how can humans avoid bullets flying at extremely high speeds with their reflection rate?
- Explain the strange 'ghost rainbow' phenomenonrainbow is a beautiful natural phenomenon that often occurs after heavy rains during the day. it is a reflection of sunlight through rain drops in the air, this phenomenon called light refraction.