using System;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace Wrox.ProCSharp.TypeView
{
class MainClass
{
static void Main()
{
Type t = typeof(double);
AnalyzeType(t);
MessageBox.Show(OutputText.ToString(), "Analysis of type " + t.Name);
Console.ReadLine();
}
static void AnalyzeType(Type t)
{
AddToOutput("Type Name: " + t.Name);
AddToOutput("Full Name: " + t.FullName);
AddToOutput("Namespace: " + t.Namespace);
Type tBase = t.BaseType;
if (tBase != null)
AddToOutput("Base Type:" + tBase.Name);
Type tUnderlyingSystem = t.UnderlyingSystemType;
if (tUnderlyingSystem != null)
AddToOutput("UnderlyingSystem Type:" + tUnderlyingSystem.Name);
AddToOutput("
PUBLIC MEMBERS:");
MemberInfo [] Members = t.GetMembers();
foreach (MemberInfo NextMember in Members)
{
AddToOutput(NextMember.DeclaringType + " " + NextMember.MemberType +
" " + NextMember.Name);
}
}
static void AddToOutput(string Text)
{
OutputText.Append("
" + Text);
}
static StringBuilder OutputText = new StringBuilder(500);
}
}
运行结果:
实例二
步骤1:新建一个类库test1,在类库下有一个类ReflectTest.cs,此类中的代码如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace test1
{
public class ReflectTest
{
public ReflectTest()
{}
public string WriteString(string s)
{
return "欢迎您," + s;
}
public static string WriteName(string s)
{
return "欢迎您光临," + s;
}
public string WriteNoPara()
{
return "您使用的是无参数方法";
}
}
public class ReflectTest_22
{ }
}
步骤2:
建立一个类test_1.cs,代码如下:
using System;
using System.Text;
using System.Reflection;
public class test1
{
public static void Main()
{
System.Reflection.Assembly ass;
Type type ;
object obj;
try
{
//ass = Assembly.LoadFile(@"D:C#学习Chapter11WhatsNewAttributes est1objDebug est1.dll");
//ass = Assembly.LoadFrom(@"D:C#学习Chapter11WhatsNewAttributes est1objDebug est1.dll");
ass = Assembly.Load("test1");
Type[] test_type1 = ass.GetTypes();
foreach (Type t1 in test_type1)
{
Console.WriteLine(t1.Name);
}
type = ass.GetType("test1.ReflectTest");//必须使用名称空间+类名称
foreach (MemberInfo MI in type.GetMembers())
{
Console.WriteLine(MI.MemberType + " " + MI.Name);
}
Console.WriteLine("*******");
MethodInfo method_1 = type.GetMethod("WriteString");//方法的名称
obj = ass.CreateInstance("test1.ReflectTest");//必须使用名称空间+类名称
string s = (string)method_1.Invoke(obj, new string[] {"jianglijun" }); //实例方法的调用
Console.WriteLine(s);
MethodInfo method_2 = type.GetMethod("WriteName");//方法的名称
s = (string)method_2.Invoke(null,new string[]{"jianglijun"}); //静态方法的调用
Console.Write(s);
MethodInfo method_3 = type.GetMethod("WriteNoPara");//无参数的实例方法
s = (string)method_3.Invoke(obj,null);
Console.WriteLine(s);
//method = null;
}
catch(Exception ex)
{
Console.WriteLine("出现错误!");
Console.WriteLine(ex);
}
finally
{
ass = null;
type = null;
obj = null;
}
}
}
运行结果如下: