An Introduction to Reflection in C#

Introduction

In this article, we will see something about reflection in .NET. First, we will see what the System.Reflectionnamespace will do for .NET developers. Reflection allows the inspection of metadata in a PE file and late binding (run time) to types and their members. The System.Reflection namespace defines the following types to analyze the module's metadata of an assembly: AssemblyModuleEnumParameterInfoMemberInfo,TypeMethodInfoConstructorInfoFieldInfoEventInfo, and PropertyInfo.

The System.Type class is the main class for reflection. The System.Type class is an abstract class and that represents a type in the Common Type System (CLR). By using this class, we can find the type name, the types used in a module (an assembly may contain one or more modules) and namespace, and to see whether a given type is a value or a reference type, and so on. It also allows us to query the type's fields, methods, properties, and events by parsing the corresponding metadata tables. FCL's Serialization mechanism uses reflection to determine what fields a type defines. The serialization formatter then can obtain the values of these fields and write them into the byte stream.


Late bindings can be achieved by using reflection. For example, in some applications, we don't know which assembly to load during compile time, so we ask the user to enter the assembly name and type during run time and the application can load assembly. For this purpose, the System.Reflection.Assembly type offers three static methods that allow you to explicitly load an assembly: LoadLoadFrom, and LoadWithPartialName. These methods are something similar to the LoadLibrary Win32 API. As our System.Reflection namespace is going to work with assembly and metadata, let's see something about assembly and metadata.

Assembly and Metadata

An assembly is a logical DLL or EXE, and a manifest is a detailed description (metadata) of an assembly. The .NET compiler produces a portable executable PE file for CLR with the extensions of .exe or .dll. This PE file is mainly comprised of metadata and IL (Intermediate Language). Metadata contains a number of different tables; for example, a type definition table, a filed definition table, a method definition table, and so forth. By parsing these tables, we can get an assembly's types and attributes. The FCL's System.Reflection namespace supports several types to reflect over or parse these metadata tables.

PE (Portable Executable) = Metadata (bunch definition tables) + IL (Microsoft Intermediate Language) + Some other data which are not relevant to this article.

Example: Reflecting Types (Querying Types)

The following code shows how to query a type for its attributes using the System.Type class. Refer to the download project ReflectionQueryTest.zip. The ReflectType(string) method takes type string and queries all attributes for that type. Call this method by sending different types as parameters. To call different Reflection classes, include using System.Reflection;

 
 
  1. using System;
  2. using System.Reflection;
  3.  
  4. namespace ReflectionQueryTest
  5. {
  6.  
  7. public class TestBaseClass {}
  8.  
  9. public class TestDerivedClass : TestBaseClass {}
  10.  
  11. struct TestStruct {}
  12.  
  13. interface TestInterface {}
  14.  
  15. class TestAttribute : System.Attribute {}
  16.  
  17. enum TestEnum {}
  18.  
  19. class Class1
  20. {
  21. private static void ReflectType(string sTypeName)
  22. {
  23. try
  24. {
  25. // get the type from the given string
  26. Type type = Type.GetType(sTypeName);
  27.  
  28. Console.WriteLine("Type name: {0}", type.FullName);
  29. Console.WriteLine("\tHasElementType = {0}",
  30. type.HasElementType);
  31. Console.WriteLine("\tIsAbstract = {0}",
  32. type.IsAbstract);
  33. Console.WriteLine("\tIsAnsiClass = {0}",
  34. type.IsAnsiClass);
  35. Console.WriteLine("\tIsArray = {0}", type.IsArray);
  36. .
  37. .
  38. .
  39.  
  40. }
  41. catch (System.NullReferenceException)
  42. {
  43. Console.WriteLine("{0} is not a valid type", sTypeName);
  44. }
  45. }
  46.  
  47. static void Main(string[] args)
  48. {
  49. // Reflect all the attributes for the given type by
  50. // passing the name of the type
  51. ReflectType("System.Int32");
  52. ReflectType("ReflectionQueryTest.TestDerivedClass");
  53. ReflectType("ReflectionQueryTest.TestStruct");
  54. ReflectType("ReflectionQueryTest.TestBaseClass");
  55.  
  56. ReflectType("ReflectionQueryTest.TestInterface");
  57. ReflectType("ReflectionQueryTest.TestAttribute");
  58. ReflectType("ReflectionQueryTest.TestEnum");
  59. }
  60. }
  61. }

Example: Parsing Types of an Assembly

In the following example, we will see how to parse the types in an assembly. To do this, follow these steps:

  1. Get the assembly name.
  2. Instantiate the assembly by using the LoadFrom method.
  3. Call the GetTypes method of the Assembly class. This method returns an array of all types of an assembly. The GetValidAssembly method checks whether the user supplied any assembly; if not, it gets the current assembly name. Include using System.Diagnostics; this is to get the current process name.
 
 
  1. private static string GetValidAssembly(string[] sAssem)
  2. {
  3. string sAssemName;
  4.  
  5. if (0 == sAssem.Length)
  6. {
  7. Process pr = Process.GetCurrentProcess();
  8. sAssemName = pr.ProcessName + ".exe";
  9. }
  10. else
  11. {
  12. sAssemName = sAssem[0];
  13. }
  14. return sAssemName;
  15. }

Call LoadFrom to load the given assembly; it's like calling LoadLibrary in the Win32 API. Then, call theGetTypes method of the assembly class, which returns an object (Type array) that contains all the types in the given assembly. See the example project found in ReflectAssembly.zip.

 
 
  1. static void Main(string[] args)
  2. {
  3. string sAssemblyName = GetValidAssembly(args);
  4. Assembly assem = Assembly.LoadFrom(sAssemblyName);
  5.  
  6. Type[] types = assem.GetTypes();
  7.  
  8. foreach (Type t in types)
  9. {
  10. try
  11. {
  12. Console.WriteLine("Type information for:" + t.FullName);
  13. Console.WriteLine("\tBase class = " + t.BaseType.FullName);
  14. Console.WriteLine("\tIs Class = " + t.IsClass);
  15. Console.WriteLine("\tIs Enum = " + t.IsEnum);
  16. Console.WriteLine("\tAttributes = " + t.Attributes);
  17. }
  18. catch (System.NullReferenceException)
  19. {
  20. Console.WriteLine("Error msg");
  21. }
  22. }
  23.  
  24. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值