Você está na página 1de 11

Reflection in .

NET 1

RELECTION IN .NET

Description

Refelction is the mechanism of discovering class information solely at run


time.Wondering where it would be useful? Imagine,you are in visual studio IDE
(Integrated devolopment environment) and as you type "object." you would see all the
methods,properties and events associated with that object.An other example would be an
Object browser.The code attached here,loads all assemblies and displays each class,its
contructors, methods, properties and events in tree view.The form also hase a command
botton (labeled More Reflection) in whose click event I create an object of MyClass1
class based on the name of the class and invoke its methods during run time.Here is an
explanation of the code with information on various classes and methods used.

I have called the name space MyReflection.Then I have declared MyClass1 and
MyClass2 which are used in the click event of More reflection Button.I will talk about
these classes when I come to the click event of this button.Next,I have called my form as
TestReflection and is inherited from System.Winforms.Form.Most of the assemblies are
found in D:\\WINNT\\Microsoft.NET\\Framework\\v1.0.2204\\.If this is not the path in
your computer change it to appropriate path on your computer.I have stored all the paths
of the assemblies in an array called arAssemblyPath.I have used System.Winforms.dll
and System.dll and commented the rest, to speed up loading and unloading of
application.I have declared an array of Types ,arOfTypes to store all the s from an
assembly.I have a for loop that loads each assembly and gets its types.To do this I had to
use Assembly class in System.Reflection name space.Let us talk a little bit about this
class before we move on.

System.Reflection.Assembly:

It defines an assembly which is a reusable,versionable and self describing building block


of a Common Language Run time application.I will discuss here only the functions that I
have used in my code.

objAssembly=System.Reflection.Assembly.LoadFrom(str);

LoadFrom function takes the path of the assembly to load and loads it and returns that
Assembly.

After loading the assembly we want to get all the types in that assembly.This class
provides a function GetTypes() (It returns an array of System.Type objects in that
assembly) which will do that for us and that line for the code is.

arOfTypes=objAssembly.GetTypes();
Reflection in .NET 2

Now having touched System.Type class,Let us talk about it.

System.Type:

This class represents type declarations.(class types, interface types, array types, value
types and enumeration types.)

It is the root of all Reflection operations.It is the primary means by which we access
metadata and it acts as a Gateway to Reflection API.It provides methods for obtaining
information about a Type declaration, such as the constructors, properties, methods and
Events.

Extracting Constructor Information:

ConstructorInfo[] ctrInfo=t.GetConstructors();
//It is an object of type System.Type. This method returns an array of objects of type
ConstructorInfo. This calss is part of System.Reflection Name space.

Extracting Properties Information:

PropertyInfo[] pInfo = t.GetProperties() ;


//It is an object of type System.Type. This method returns an array of objects of type
PropertyInfo. This calss is part of System.Reflection Name space.

Extracting Method Information:

MethodInfo[] mInfo=t.GetMethods();

Extracting Event Information:

EventInfo[] eInfo=t.GetEvents();

Once I get all this info,I am presenting it in a tree view control.This should fairly give a
good idea of getting information about a Type.

Once you know all the information about a class,What do you want to do?Probably you
want to creat an instance of that class and execute one of its methods.I have created two
classes MyClass1 and MyClass2 as part of this name space and in the click event of More
reflection button I have created an instance of each of these classes and invoked its
methods.I have put message boxes so that we would know that they are getting
executed.Let us look at this code.

Type t= Type.GetType("MyReflection.MyClass1");

I have passed the name of the class to static method GetType of Type class which would
Reflection in .NET 3

return me a type Object of type MyClass1.Once you get Type object,as mentioned before
you could do lot of things with it.Let us look at Activator class and see what we can do
with this class and Type class.

System.Activator:

This class contains methods to create types of objects locally or remotely or obtain
references to existing objects.I have used CreateInstance() of this class to create an
instance of MyClass1.This method needs a Type object as argument to creat an instance
of that type.It returns an object.Next I have used GetType() on object and then used
InvokeMember() on the Type object to invoke method M1 of MyClass1.Here is that
piece of code.

obj1=Activator.CreateInstance(t);
obj1.GetType().InvokeMember("M1",BindingFlags.Default
|BindingFlags.InvokeMethod,null,obj1,new object[]{});

Many languages and runtime environments provide some type of runtime type
information: the ability to get detailed information about classes, fields, methods,
properties, and other code elements at runtime. With C++ and Delphi programs you have
to specifically enable that support. The Java runtime environment has it built in, and type
libraries provide the information for Component Object Model (COM) objects. Runtime
type information is available in .NET programs, too. The information is stored as
metadata in the compiled assembly and is accessible through classes defined in the
<tt>System.Reflection</tt> namespace.

Using .NET Reflection, you can discover pretty much everything about an assembly and
the classes, interfaces, and value types that it contains. You can use the resulting
information to instantiate types, call methods, access properties, and even peek at private
members. Reflection is powerful, useful, and potentially dangerous.

The common language runtime loader manages application domains. This management
includes loading each assembly into the appropriate application domain and controlling
the memory layout of the type hierarchy within each assembly.

Assemblies contain modules, modules contain types, and types contain members.
Reflection provides objects that encapsulate assemblies, modules, and types. You can use
reflection to dynamically create an instance of a type, bind the type to an existing object,
or get the type from an existing object. You can then invoke the type's methods or access
its fields and properties. Typical uses of reflection include the following:

• Use Assembly to define and load assemblies, load modules that are listed in the
assembly manifest, and locate a type from this assembly and create an instance of it.
Reflection in .NET 4

• Use Module to discover information such as the assembly that contains the
module and the classes in the module. You can also get all global methods or other
specific, nonglobal methods defined on the module.

• Use ConstructorInfo to discover information such as the name, parameters, access


modifiers (such as public or private), and implementation details (such as abstract
or virtual) of a constructor. Use the GetConstructors or GetConstructor method of a
Type to invoke a specific constructor.

• Use MethodInfo to discover information such as the name, return type,


parameters, access modifiers (such as public or private), and implementation details
(such as abstract or virtual) of a method. Use the GetMethods or GetMethod
method of a Type to invoke a specific method.

• Use FieldInfo to discover information such as the name, access modifiers (such as
public or private) and implementation details (such as static) of a field, and to get
or set field values.

• Use EventInfo to discover information such as the name, event-handler data type,
custom attributes, declaring type, and reflected type of an event, and to add or
remove event handlers.

• Use PropertyInfo to discover information such as the name, data type, declaring
type, reflected type, and read-only or writable status of a property, and to get or set
property values.

• Use ParameterInfo to discover information such as a parameter's name, data type,


whether a parameter is an input or output parameter, and the position of the
parameter in a method signature.

The classes of the System.Reflection.Emit namespace provide a specialized form of


reflection that enables you to build types at run time.

Reflection can also be used to create applications called type browsers, which enable
users to select types and then view the information about those types.

There are other uses for reflection. Compilers for languages such as JScript use reflection
to construct symbol tables. The classes in the System.Runtime.Serialization namespace
use reflection to access data and to determine which fields to persist. The classes in the
System.Runtime.Remoting namespace use reflection indirectly through serialization.
Reflection in .NET 5

The System.Type class is central to reflection. The common language runtime creates the
Type for a loaded type when reflection requests it. You can use a Type object's methods,
fields, properties, and nested classes to find out everything about that type.

Use Assembly.GetType or Assembly.GetTypes to obtain Type objects from assemblies


that have not been loaded, passing in the name of the type or types you want. Use
Type.GetType to get the Type objects from an assembly that is already loaded. Use
Module.GetType and Module.GetTypes to obtain module Type objects.

The following example shows the syntax necessary to get the Assembly object and
module for an assembly.
[C#]
// Gets the mscorlib assembly in which the object is defined.
Assembly a = typeof(Object).Module.Assembly;

The following example demonstrates getting Type objects from a loaded assembly.
[C#]
// Loads an assembly using its file name.
Assembly a = Assembly.LoadFrom ("MyExe.exe");
// Gets the type names from the assembly.
Type [] types2 = a.GetTypes ();
foreach (Type t in types2)
{
Console.WriteLine (t.FullName);
}

Once you obtain a Type, there are many ways you can discover information about the
members of that type. For example, you can find out about all the type's members by
calling the Type.GetMembers method, which obtains an array of MemberInfo objects
describing each of the members of the current type.

You can also use methods on the Type class to retrieve information about one or more
constructors, methods, events, fields, or properties that you specify by name. For
example, Type.GetConstructor encapsulates a specific constructor of the current class.

If you have a Type, you can use the Type.Module property to obtain an object that
encapsulates the module containing that type. Use the Module.Assembly property to
Reflection in .NET 6

locate an object that encapsulates the assembly containing the module. You can obtain
the assembly that encapsulates the type directly by using the Type.Assembly property.

System.Type and ConstructorInfo


The following example shows how to list the constructors for a class, in this case, the
String class.
[C#]
// This program lists all the public constructors
// of the System.String class.
using System;
using System.Reflection;
class ListMembers {
public static void Main(String[] args) {
Type t = typeof(System.String);
Console.WriteLine ("Listing all the public constructors of the {0} type", t);
// Constructors.
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();
}
}

MemberInfo, MethodInfo, FieldInfo, and PropertyInfo


Obtain information about the type's methods, properties, events, and fields using
MemberInfo, MethodInfo, FieldInfo, or PropertyInfo objects.
Reflection in .NET 7

The following example uses MemberInfo to list the number of members in the
System.IO.File class and uses the System.Type.IsPublic property to determine the
visibility of the class.
[C#]
using System;
using System.IO;
using System.Reflection;

class Mymemberinfo
{
public static void Main(string[] args)
{
Console.WriteLine ("\nReflection.MemberInfo");
// Gets the Type and MemberInfo.
Type MyType =Type.GetType("System.IO.File");
MemberInfo[] Mymemberinfoarray = MyType.GetMembers();
// Gets and displays the DeclaringType method.
Console.WriteLine("\nThere are {0} members in {1}.",
Mymemberinfoarray.Length, MyType.FullName);
Console.WriteLine("{0}.", MyType.FullName);
if (MyType.IsPublic)
{
Console.WriteLine("{0} is public.", MyType.FullName);
}
}
}

The following example investigates the type of the specified member. It performs
reflection on a member of the MemberInfo class, and lists its type.
[C#]
// This code displays information about the GetValue method of FieldInfo.
using System;
using System.Reflection;
Reflection in .NET 8

class MyMethodInfo {
public static int Main() {
Console.WriteLine("Reflection.MethodInfo");
// Gets and displays the Type.
Type MyType = Type.GetType("System.Reflection.FieldInfo");
// Specifies the member for which you want type information.
MethodInfo Mymethodinfo = MyType.GetMethod("GetValue");
Console.WriteLine(MyType.FullName + "." + Mymethodinfo.Name);
// Gets and displays the MemberType property.
MemberTypes Mymembertypes = Mymethodinfo.MemberType;
if (MemberTypes.Constructor == Mymembertypes) {
Console.WriteLine("MemberType is of type All");
}
else if (MemberTypes.Custom == Mymembertypes) {
Console.WriteLine("MemberType is of type Custom");
}
else if (MemberTypes.Event == Mymembertypes) {
Console.WriteLine("MemberType is of type Event");
}
else if (MemberTypes.Field == Mymembertypes) {
Console.WriteLine("MemberType is of type Field");
}
else if (MemberTypes.Method == Mymembertypes) {
Console.WriteLine("MemberType is of type Method");
}
else if (MemberTypes.Property == Mymembertypes) {
Console.WriteLine("MemberType is of type Property");
}
else if (MemberTypes.TypeInfo == Mymembertypes) {
Console.WriteLine("MemberType is of type TypeInfo");
}
return 0;
}
Reflection in .NET 9

The following example uses all the Reflection *Info classes along with BindingFlags to
list all the members (constructors, fields, properties, events, and methods) of the specified
class, dividing the members into static and instance categories.
[C#]
// This program lists all the members of the
// System.IO.BufferedStream class.
using System;
using System.IO;
using System.Reflection;

class ListMembers {
public static void Main(String[] args) {
// Specifies the class.
Type t = typeof (System.IO.BufferedStream);
Console.WriteLine ("Listing all the members (public and non public) of the {0}
type", t);

// Lists static fields first.


FieldInfo [] fi = t.GetFields (BindingFlags.Static |
BindingFlags.NonPublic | BindingFlags.Public);
Console.WriteLine ("// Static Fields");
PrintMembers (fi);

// Static properties.
PropertyInfo [] pi = t.GetProperties (BindingFlags.Static |
BindingFlags.NonPublic | BindingFlags.Public);
Console.WriteLine ("// Static Properties");
PrintMembers (pi);

// Static events.
EventInfo [] ei = t.GetEvents (BindingFlags.Static |
BindingFlags.NonPublic | BindingFlags.Public);
Reflection in .NET 10

Console.WriteLine ("// Static Events");


PrintMembers (ei);

// Static methods.
MethodInfo [] mi = t.GetMethods (BindingFlags.Static |
BindingFlags.NonPublic | BindingFlags.Public);
Console.WriteLine ("// Static Methods");
PrintMembers (mi);

// Constructors.
ConstructorInfo [] ci = t.GetConstructors (BindingFlags.Instance |
BindingFlags.NonPublic | BindingFlags.Public);
Console.WriteLine ("// Constructors");
PrintMembers (ci);

// Instance fields.
fi = t.GetFields (BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
Console.WriteLine ("// Instance Fields");
PrintMembers (fi);

// Instance properites.
pi = t.GetProperties (BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
Console.WriteLine ("// Instance Properties");
PrintMembers (pi);

// Instance events.
ei = t.GetEvents (BindingFlags.Instance | BindingFlags.NonPublic |
BindingFlags.Public);
Console.WriteLine ("// Instance Events");
PrintMembers (ei);
Reflection in .NET 11

// Instance methods.
mi = t.GetMethods (BindingFlags.Instance | BindingFlags.NonPublic
| BindingFlags.Public);
Console.WriteLine ("// Instance Methods");
PrintMembers (mi);

Console.WriteLine ("\r\nPress ENTER to exit.");


Console.Read();
}

public static void PrintMembers (MemberInfo [] ms) {


foreach (MemberInfo m in ms) {
Console.WriteLine ("{0}{1}", " ", m);
}
Console.WriteLine();
}
}

Você também pode gostar