Kamis, 08 November 2007

Aneka makanan Reflection,Methodinfo,MethodBody,Constructorinfo

public class Cobacoba
{
private void Lemparbatu(string batunya, int jumlahnya)
{

}
public int LemparbatuReturn(string batunya, int jumlahnya)
{
int hak = 0;
string tipenya = "sepatu";
try
{
Console.WriteLine("Lemparbatu return executed,Nilai params=>batunya: {0} jumlahnya: {1}", batunya, jumlahnya);
return jumlahnya;
}
catch (InvalidProgramException ex)
{

}
catch (ApplicationException eb)
{ }
return jumlahnya;
}
}
class Program
{
static void Main(string[] args)
{
MethodInfo m = typeof(Cobacoba).GetMethod("LemparbatuReturn");
//nyari tipe return
Type tipereturnnya = m.ReturnType;
Console.WriteLine(tipereturnnya.ToString());
//nyari tipe parameter
foreach (ParameterInfo param in m.GetParameters())
{
Console.WriteLine(param.Name + " " + param.ParameterType.ToString());
}
/*this shows the invoke Member*/
Cobacoba ttg=new Cobacoba();
MethodInfo method = typeof(Cobacoba).GetMethod("LemparbatuReturn");
/*the usage of methodbody*/
MethodBody mb= method.GetMethodBody();
IList x = mb.LocalVariables;
IList n = mb.ExceptionHandlingClauses;
/*the usage of Constructor Info*/
ConstructorInfo ci = typeof(string).GetConstructor(new Type[] { typeof(char[]) });
string s = (string)ci.Invoke(new object[] { new char[] { 'H', 'E', 'L', 'L', 'O' } });
Console.WriteLine(s);
Type tem = ttg.GetType();
string f="granit";
int g=3;
object[] t=new object[2];
t[0]=(Object) f;
t[1]=(Object) g;
try
{
tem.InvokeMember("LemparbatuReturn", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, null, ttg, t);
}
catch (TargetInvocationException ex)
{
//do something Here
}
Console.ReadLine();
}
}

1 komentar:

salcad mengatakan...

Emang nya di keyboard ada Tab dan Space untuk pajangan mas...hehehehe....