Monday, July 23, 2007

Reflection: Basics, Code Listing

Reflection:
• Reflection provides objects that encapsulate assemblies, modules and types
• Reflection can be used to dynamically create an object of the class
• Bind an object to a class, or get type from an object
• Also invoke the object’s methods and access its field and properties

Uses:
• Use Assembly to load and define assembly
• Load modules that are listed in the assemly manifest
• See inside a module to find out assembly that contains the module and classes inside that module
• Classes in System.Reflection.Emit allow to build types at runtime

Viewing Type Information:
• System.Type class is central to reflection. CLR runtime creates the Type for a loaded type when reflection requests it
• Use Assembly.GetType or GetTypes to obtain Type objects from assemblies that have not been loaded

Code Listing: Reflection:

using System;
using System.Reflection;

class ListMembers
{
public static void Main(Stringp[] args)
{
Type t = typeof(System.String);
Console.WriteLine(“Listing public constructors of the {0} type ”, t);

ConstructorInfo[] ci = t.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
Console.WriteLine(“Constructors”);
PrintMembers(ci);
}

public static void PrintMembers(MemberInfo[] ms)
{
foreach(MemberInfo m in ms)
{
Console.WriteLine(“{0}{1}”, “ “, m);
}
Console.WriteLine();

}

}

No comments:

Post a Comment