.Net 反射 1

 如何汲取构造函数信息:

    ConstructorInfo[] ctrInfo = t.GetConstructors(); //这是个System.Type类型的对象。这个方法返回的是构造函数信息的对象数组。这个类是命名空间System.Reflection的一部分。

如何获取属性信息:

   PropertyInfo[] pInfo = t.GetProperties();//这是System.Type类型的实例。这方法返回的实对象属性信息的对象数组,它是System.Reflection命名空间中的一个类。

如何获取方法信息:

   MethodInfo[] mInfo = t..GetMethods();

如何获取事件信息:

   EventInfo[] eInfo = t.GetEvents();

我将把这些信息在一棵树上展示出来。这应该可以给我一个关于这个类型信息清晰的轮廓。

你有了这些信息之后,那么你现在想做些什么呢?有可能你想创建一个类型实例并且执行一个方法。我在MyReflection命名空里创建了MyClass1和MyClass2这两个类,并且在Button的Click事件里我已经创建了每个类的实例也调用了他的方法。我弹出消息框一边让自己知道他们放确实被执行了。接下来让我们来看一下代码吧。

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

我以类名称作为静态方法GetType的参数,他将返回MyClass1的类型。一旦你有了对象的类型,你将可以想之前说的一样做很多事情了。再让我们看一下Activator这个类,看一下我们能拿这个类和Type做些什么。

System.Activator:

    这个类包含一些将要在本地或者远程创建的对象的类型的方法或者还可以获得存在对象的引用。我使用这个类的CreateInstance()方法创建了MyClass1的实例。这个方法需要一个类型对象作为参数创建类型实例,然后返回实例对象。下一步,我使用了对象的GetType()方法然后使用了Type类型对象上的InvokeMember()方法调用Myclass1的M1方法,请看一下代码:

obj1 = Activator.CreateInstance(t);

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

需要什么才能够编译? .Net SDK

怎么编译? csc /r:System.dll /r:System.winforms.dll /r:Microsoft.win32.interop.dll
/r:System.Drawing.dll TestReflection.cs

源代码:

namespace MyReflection
{
using
System;
using
System.Drawing;
using
System.Collections;
using
System.ComponentModel;
using
System.WinForms;
using
System.Reflection;
//
//MyClass1 and MyClass2 are used to demonstrate the some other aspects of reflection
//such as creating an instace of object at run time based on class name and invoking a method of that object
//see cmdMoreReflection_Click() for these aspects
class
MyClass1
{
public
MyClass1()
{
//Console.WriteLine("In Constructor of MyClass1");
MessageBox.Show("In Constructor of MyClass1");
}
public void
M1()
{
//Console.WriteLine("In M1");
MessageBox.Show("In M1");
}
}
class
MyClass2
{
public
MyClass2()
{
//Console.WriteLine("In Constructor of MyClass2");
MessageBox.Show("In Constructor of MyClass2");
}
public void
M2()
{
//Console.WriteLine("In M2");
MessageBox.Show("In M2");
}
}
//
//
///
<summary>
///
Summary description for TestReflection.
///
</summary>
public class
TestReflection : System.WinForms.Form
{
///
<summary>
///
Required designer variable.
///
</summary>
private
System.ComponentModel.Container components;
private
System.WinForms.Label label1;
private
System.WinForms.Button cmdReflect;
private
System.WinForms.TreeView tvwObjectBrowser;
public
TestReflection()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
//common prefix for the path of assemblies.
//If this is not same on your computers you need to change this
String strPrefixForPath = "D://WINNT//Microsoft.NET//Framework//v1.0.2204//";
//Array for holding path names for all assemblies
//If you have a new assembly Increase the size of this array
//and add the path to the array
string
[] arAssemblyPath =
{
strPrefixForPath + "System.Winforms.dll",
strPrefixForPath + "System.dll"
/*strPrefixForPath + "mscorlib.dll",
strPrefixForPath + "Microsoft.ComServices.dll",
strPrefixForPath + "Microsoft.Win32.Interop.dll",
strPrefixForPath + "System.ComponentModel.Design.dll",
strPrefixForPath + "System.configuration.dll",
strPrefixForPath + "System.configuration.Design.dll",
strPrefixForPath + "System.configuration.Install.dll",
strPrefixForPath + "System.Data.dll",
strPrefixForPath + "System.Data.Design.dll",
strPrefixForPath + "System.Diagnostics.Design.dll",
strPrefixForPath + "System.Diagnostics.dll",
strPrefixForPath + "System.DirectoryServices.dll",
strPrefixForPath + "System.dll",
strPrefixForPath + "System.Drawing.dll",
strPrefixForPath + "System.Drawing.Design.dll",
strPrefixForPath + "System.Drawing.Printing.Design.dll",
strPrefixForPath + "System.IO.dll",
strPrefixForPath + "System.Management.dll",
strPrefixForPath + "System.Messaging.dll",
strPrefixForPath + "System.Net.dll",
strPrefixForPath + "System.Runtime.Remoting.dll",
strPrefixForPath + "System.Runtime.Serialization.Formatters.Soap.dll",
strPrefixForPath + "System.Security.dll",
strPrefixForPath + "System.ServiceProcess.dll",
strPrefixForPath + "System.Text.RegularExpressions.dll",
strPrefixForPath + "System.Timers.dll",
strPrefixForPath + "System.Web.dll",
strPrefixForPath + "System.Web.UI.Design.dll",
strPrefixForPath + "System.XMl.dll",
strPrefixForPath + "System.Xml.Serialization.dll" */
};
//strPrefixForPath + "System.WebServices.Design.dll",
Type[] arOfTypes;
//Array of Types.This array would hold all the types from each assembly
Assembly objAssembly;
//An assembly object so that each assembly could be assinged to it
//Load each assembly
foreach(string str in
arAssemblyPath)
{
try
//In case we dont find the essembly,capture the exception
{
objAssembly=System.Reflection.Assembly.LoadFrom(str);
arOfTypes=objAssembly.GetTypes();
//For Each type in arOfTypes get Properties,Methods and Events
foreach(Type t in
arOfTypes )
{
//Add the class as one of the roots of the treeview
TreeNode tn;
tn=tvwObjectBrowser.Nodes.Add(t.FullName);
//Get Constructors
ConstructorInfo[] ctrInfo=t.GetConstructors();
TreeNode tn2;
tn2=tn.Nodes.Add("Constructors");
foreach(ConstructorInfo c in
ctrInfo)
{
tn2.Nodes.Add(c.ToString());
}
//Get Properties
try
{
PropertyInfo[] pInfo = t.GetProperties() ;
tn2=tn.Nodes.Add("Properties");
foreach(PropertyInfo p in
pInfo)
{
tn2.Nodes.Add(p.ToString());
}
}
catch
(Exception e)
{
tn2=tn.Nodes.Add("Properties");
tn2.Nodes.Add(e.ToString());
}
//Get Methods
try
{
MethodInfo[] mInfo=t.GetMethods();
tn2=tn.Nodes.Add("Methods");
foreach(MethodInfo m in
mInfo)
{
tn2.Nodes.Add(m.ToString());
}
}
catch
(Exception e)
{
tn2=tn.Nodes.Add("Methods");
tn2.Nodes.Add(e.ToString());
}
//Get Events
try
{
EventInfo[] eInfo=t.GetEvents();
tn2=tn.Nodes.Add("Events");
foreach(EventInfo e in
eInfo)
{
tn2.Nodes.Add(e.ToString());
}
}
catch
(Exception e)
{
tn2=tn.Nodes.Add("Events");
tn2.Nodes.Add(e.ToString());
}
}
}
catch
(Exception e)
{
MessageBox.Show(e.ToString());
}
}
arOfTypes=
null
;
objAssembly=
null
;
}
///
<summary>
///
Clean up any resources being used.
///
</summary>
public override void
Dispose()
{
base
.Dispose();
components.Dispose();
}
///
<summary>
///
Required method for Designer support - do not modify
///
the contents of this method with the code editor.
///
</summary>
private void
InitializeComponent()
{
this.components = new
System.ComponentModel.Container ();
this.label1 = new
System.WinForms.Label ();
this.cmdReflect = new
System.WinForms.Button ();
this.tvwObjectBrowser = new
System.WinForms.TreeView ();
//@this.TrayHeight = 0;
//@this.TrayLargeIcon = false;
//@this.TrayAutoArrange = true;
label1.Location = new
System.Drawing.Point (16, 264);
label1.Text = "Click on this button Which Demonstartes some more aspects of reflection such as creating an object at run time based on class name and invoking a method of that object";
label1.Size =
new
System.Drawing.Size (224, 48);
label1.ForeColor = System.Drawing.Color.Blue;
label1.TabIndex = 2;
label1.Anchor = System.WinForms.AnchorStyles.Bottom;
cmdReflect.Location =
new
System.Drawing.Point (256, 272);
cmdReflect.ForeColor = System.Drawing.Color.Blue;
cmdReflect.Size =
new
System.Drawing.Size (96, 24);
cmdReflect.TabIndex = 1;
cmdReflect.Anchor = System.WinForms.AnchorStyles.Bottom;
cmdReflect.Text = "More Reflection";
cmdReflect.Click +=
new System.EventHandler (this
.cmdReflect_Click);
tvwObjectBrowser.Location =
new
System.Drawing.Point (16, 16);
tvwObjectBrowser.Size =
new
System.Drawing.Size (336, 240);
tvwObjectBrowser.TabIndex = 0;
tvwObjectBrowser.Anchor = System.WinForms.AnchorStyles.All;
this
.Text = "Reflection";
this.AutoScaleBaseSize = new
System.Drawing.Size (5, 13);
this.ClientSize = new
System.Drawing.Size (368, 317);
this.Controls.Add (this
.label1);
this.Controls.Add (this
.cmdReflect);
this.Controls.Add (this
.tvwObjectBrowser);
}
protected void cmdReflect_Click (object
sender, System.EventArgs e)
{
Type t=Type.GetType("MyReflection.MyClass1");
object
obj1;
obj1=Activator.CreateInstance(t);
obj1.GetType().InvokeMember("M1",BindingFlags.Default |BindingFlags.InvokeMethod,
null,obj1,new object
[]{});
Type t2=Type.GetType("MyReflection.MyClass2");
object
obj2;
obj2=Activator.CreateInstance(t2);
obj2.GetType().InvokeMember("M2",BindingFlags.Default |BindingFlags.InvokeMethod,
null,obj2,new object
[]{});
}
///
<summary>
///
The main entry point for the application.
///
</summary>
public static void Main(string
[] args)
{
Application.Run(
new
TestReflection());
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值