|
Reflection provides objects (of type Type) 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 and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables you to access them. For more information,
Reflection is accessing details of an object through the RTTI (run-time type information) - specifically Type; it is used primarily when you can't *possibly* know the specifics at compile-time, for example in data-binding (usually via System.ComponentModel as an intermediary) or some factory patterns:
Reflection is useful in the following situations:
->For building new types at runtime. Use classes in System.Reflection.Emit.
->For performing late binding, accessing methods on types created at run time. See the topic Dynamically Loading and Using Types.
->When you need to access attributes in your program's metadata. See the topic Accessing Attributes With Reflection.
->For examining and instantiating types in an assembly.
EXAMPLE
Here's a simple example of Reflection using the static method GetType - inherited by all types from the Object base class - to obtain the type of a variable:
C#
Copy
// Using GetType to obtain type information:
int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);
The output is:
System.Int32
In this example, Reflection is used to obtain the full name of a loaded assembly:
C#
Copy
// Using Reflection to get information from an Assembly:
System.Reflection.Assembly o = System.Reflection.Assembly.Load("mscorlib.dll");
System.Console.WriteLine(o.GetName());
CODE SNIPPET
using System;
class Foo {
public string Bar { get; set; }
public void DoSomething(string caption)
{
Console.WriteLine(caption + ": " + Bar);
}
}
static class Program
{
static void Main()
{
Type type = typeof(Foo);
object obj = type.GetConstructor(Type.EmptyTypes).Invoke(null);
type.GetProperty("Bar").SetValue(obj, "Hello world", null);
type.GetMethod("DoSomething").Invoke(obj, new object[] {"Reflection says"});
}
}
|