One very useful feature related to reflection is the ability
to create object dynamically and call methods on them. You can specify which
class you want a Type object, or by giving the name of an assembly and a class
as string, so this makes it possible to get the name of a class from the user
and create an object of the appropriate type. You can then interact with the
new object just as if you’d created it with new, and use reflection to find out
just you’re dealing with and what it can do.
Following C# code will demonstrate the reflection capabilities.
namespace
reflect
{
using System ;
using System.Reflection ;
publicclass ClassA
{
publicstaticint
Main ( string[] kami )
{
Type t = typeof( test ) ;
Console.WriteLine ( "Type of class: " + t ) ;
Console.WriteLine ( "Namespace: " + t.Namespace ) ;
ConstructorInfo[] ci = t.GetConstructors( );
Console.WriteLine( "Constructors are:" ) ;
foreach( ConstructorInfo i in ci )
{
Console.WriteLine( i ) ;
}
PropertyInfo[] pi = t.GetProperties( );
Console.WriteLine( "Properties are:" ) ;
foreach( PropertyInfo i in
pi )
{
Console.WriteLine( i ) ;
}
MethodInfo[] mi = t.GetMethods( ) ;
Console.WriteLine( "Methods are:" ) ;
foreach( MethodInfo i in mi )
{
Console.WriteLine( "Name: " + i.Name ) ;
ParameterInfo[] pif = i.GetParameters () ;
foreach ( ParameterInfo p
in pif )
{
Console.WriteLine("Type:
" + p.ParameterType + " parameter name: " + p.Name ) ;
}
}
return 0 ;
}
}
publicclass test
{
int i ;
int prop;
publicint Prop
{
get
{
return prop ;
}
set
{
prop
= value ;
}
}
public test()
{
}
public test ( int
x )
{
i = x ;
}
publicint funcA
( int x )
{
Console.WriteLine ( x ) ;
return 2 * x ;
}
}
}
Comments