Reflection in C ++

Source: Internet
Author: User

 

Http://msdn.microsoft.com/zh-cn/library/y0114hz2.aspx

 

Updated: February 1, November 2007

Reflection allows you to check for known data types at runtime. For example, Reflection allows enumeration of data types in a given assembly, and you can find members of a given class or value type. This applies no matter whether the type is known or referenced during compilation. This makes reflection a useful feature of development and code management tools.

Note that the provided Assembly name is strongly named (see Assembly with strong names), including the Assembly version, culture, and signature information. You can also retrieve the name of The namespace that defines the data type and the name of the base class.

To access the reflection function, the most common method is to use the GetType method. This method is provided by system: object and is derived from all garbage collection classes.

If. EXE is used/CLR: pureOr/CLR: safeThe reflection on. EXE generated using the Visual C ++ compiler is allowed. For more information, see/CLR (Common Language Runtime Library compilation ).

The topic in this section:

  • How to: Use reflection to implement the plug-in component structure

  • How to: Use reflection to enumerate Data Types in an assembly

For more information, see

  • Reflection

  • System. Reflection namespace

Example

The GetType method returns a pointer to a type object, which describes the type of the object based on. (The "type" object does not contain any instance-specific information .) The full name of the type is such an object, which may be displayed as follows:

Note that the type name includes the entire type definition range (including the namespace) and is displayed in. Net syntax (using the period number as the range parsing operator ).

// vcpp_reflection.cpp// compile with: /clrusing namespace System;int main() {   String ^ s = "sample string";   Console::WriteLine("full type name of '{0}' is '{1}'", s, s->GetType());}

Full type name of 'sample string' is 'System. string'

Value types can also be used with the GetType function, but they must be packed first.

// vcpp_reflection_2.cpp// compile with: /clrusing namespace System;int main() {   Int32 i = 100;    Object ^ o = i;   Console::WriteLine("type of i = '{0}'", o->GetType());}

Type of I = 'System. int32'

Like the GetType method, the typeid operator returns a pointer to the "type" object, so this code indicates the type nameSystem. int32. The most basic function of reflection is to display the type name, but a more useful technique is to check or find the valid values of enumeration types. You can use staticEnum: getnamesFunction. This function returns a string array. Each string contains an enumerated value in the text format. The following example retrieves a string array that describes the enumerated values of the "options" (CLR) enumeration and displays these values in a loop.

If you add the fourth option to the "options" enumeration, this code reports new options without recompilation (even if the enumeration is defined in a separate set ).

// vcpp_reflection_3.cpp// compile with: /clrusing namespace System;enum class Options {   // not a native enum   Option1, Option2, Option3};int main() {   array<String^>^ names = Enum::GetNames(Options::typeid);   Console::WriteLine("there are {0} options in enum '{1}'",                names->Length, Options::typeid);   for (int i = 0 ; i < names->Length ; i++)      Console::WriteLine("{0}: {1}", i, names[i]);   Options o = Options::Option2;   Console::WriteLine("value of 'o' is {0}", o);}

there are 3 options in enum 'Options'0: Option11: Option22: Option3value of 'o' is Option2

The GetType object supports a large number of checks for type members and attributes. This code retrieves and displays part of this information:

// vcpp_reflection_4.cpp// compile with: /clrusing namespace System;int main() {   Console::WriteLine("type information for 'String':");   Type ^ t = String::typeid;   String ^ assemblyName = t->Assembly->FullName;   Console::WriteLine("assembly name: {0}", assemblyName);   String ^ nameSpace = t->Namespace;   Console::WriteLine("namespace: {0}", nameSpace);   String ^ baseType = t->BaseType->FullName;   Console::WriteLine("base type: {0}", baseType);   bool isArray = t->IsArray;   Console::WriteLine("is array: {0}", isArray);   bool isClass = t->IsClass;   Console::WriteLine("is class: {0}", isClass);}

type information for 'String':assembly name: mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089namespace: Systembase type: System.Objectis array: Falseis class: True

Reflection also allows enumeration of types and members in classes in an assembly. To illustrate this function, define a simple class:

// vcpp_reflection_5.cpp// compile with: /clr /LDusing namespace System;public ref class TestClass {   int m_i;public:   TestClass() {}   void SimpleTestMember1() {}   String ^ SimpleMember2(String ^ s) { return s; }    int TestMember(int i) { return i; }   property int Member {      int get() { return m_i; }      void set(int i) { m_i = i; }   }};

If you have compiled the above code into a DLL called vcpp_reflection_6.dll, you can use reflection to check the content of this Assembly. This includes using the static reflection API function Assembly: load to load the assembly. This function returnsAssemblyThe address of the object, and then it can query information about the module and type in the object.

Once the reflection system successfully loads the assembly, it uses the Assembly: gettypes function to retrieve the array of the "type" object. Each array element contains information about different types (although only one class is defined in this example ). UseType: getmembersThe function queries information about type members for each "type" in this array. This function returnsMethodinfoAn array of objects. Each object contains information about member functions, data members, or attributes of the type.

Note that the method List is included inTestclassExplicitly defined functions andSystem: ObjectClass implicit inheritance function. When using. Net (instead of using Visual C ++ syntax) for description, the attribute is displayed as a basic data member accessed by the get/set function. The get/set function is displayed as a rule method in this list. The entire Common Language Runtime Library supports reflection, but the Visual C ++ compiler does not.

Although you use this code to check the defined assembly, you can also use this code to check the. NET assembly. For example, if you change testassembly to mscorlib, you will see a list of each type and method defined in mscorlib. dll.

// vcpp_reflection_6.cpp// compile with: /clrusing namespace System;using namespace System::IO;using namespace System::Reflection;int main() {   Assembly ^ a = nullptr;   try {      // load assembly -- do not use file extension      // will look for .dll extension first      // then .exe with the filename      a = Assembly::Load("vcpp_reflection_5");   }   catch (FileNotFoundException ^ e) {      Console::WriteLine(e->Message);      return -1;   }   Console::WriteLine("assembly info:");   Console::WriteLine(a->FullName);   array<Type^>^ typeArray = a->GetTypes();   Console::WriteLine("type info ({0} types):", typeArray->Length);   int totalTypes = 0;   int totalMembers = 0;   for (int i = 0 ; i < typeArray->Length ; i++) {      // retrieve array of member descriptions      array<MemberInfo^>^ member = typeArray[i]->GetMembers();      Console::WriteLine("  members of {0} ({1} members):",       typeArray[i]->FullName, member->Length);      for (int j = 0 ; j < member->Length ; j++) {         Console::Write("       ({0})",          member[j]->MemberType.ToString() );         Console::Write("{0}  ", member[j]);         Console::WriteLine("");         totalMembers++;      }      totalTypes++;   }   Console::WriteLine("{0} total types, {1} total members",   totalTypes, totalMembers);}

 

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.