您的位置:首页 > 编程语言 > C#

分享一段C#反射代码-[Type是反射的入口]--[查看类型信息]--[动态生成对象]

2011-09-28 10:02 489 查看
反射是一个非常强大的机制。利用它可以动态的生成一个对象。还可以查看作用到类型上的Attribute。

当然了,利用反射在效率上会有些影响,但没有反射许多地方真的不容易实现,甚至实现不了,所以说要辨证的去看待这个问题。

下面贴一段非常简单的代码,查看了类型,查看了类型中的成员信息。

//程序集-包含->模块-包含->类型-包含->元素

代码如下:

using System;
using System.Reflection;

namespace zuo_TestReflectionProject{

#region "程序入口"
public class Program{
static void Main(){
People pa = new People("鸿蒙","道人",3600);
Console.WriteLine(pa);
Console.WriteLine(new string('-',40));

Type tx = pa.GetType();	//反射入口,获取类型
Console.WriteLine("类型名:{0}\n",tx.Name);
Console.WriteLine("全名称:{0}\n",tx.FullName);
Console.WriteLine(new string('-',40));

object[] what = tx.GetCustomAttributes(typeof(SoftInfoAttribute),false);	//将作用在这个类型上的特性提取出来
foreach(SoftInfoAttribute si in what){	//遍历特性项
Console.WriteLine(si.InfoType);
Console.WriteLine(si.Author);
Console.WriteLine(si.Dm);
if(!String.IsNullOrEmpty(si.Memo)){
Console.WriteLine(si.Memo);
}
Console.WriteLine(new string('-',40));
}

MethodInfo[] mis = tx.GetMethods(
                              BindingFlags.Instance
                              |BindingFlags.Static
                              |BindingFlags.Public
                              |BindingFlags.NonPublic
                              |BindingFlags.DeclaredOnly);	//将其所有的方法都列出来
Console.WriteLine("列出其所有的方法:\n");
foreach(MethodInfo mi in mis){
Console.WriteLine("方法名:{1} {2} {0}();",mi.Name,mi.MemberType,mi.ReturnType);

                     //查看方法上是否有被作用的特性
object[] metAttribute = mi.GetCustomAttributes(typeof(SoftInfoAttribute),false);
foreach(SoftInfoAttribute ss in metAttribute){	//列出作用在方法上的特性项
Console.WriteLine("\t{0} {1} {2} {3}",ss.InfoType,ss.Author,ss.Dm,ss.Memo);
}
}
Console.WriteLine("\n\n");
Assembly currentAssembly = Assembly.GetExecutingAssembly();	//载入程序集,当前程序集
Console.WriteLine("当前程序集的名称:{0}",currentAssembly.FullName);

Console.WriteLine("\n当前程序集的模块:");
Module[] MyModules = currentAssembly.GetModules();	//获取模块
foreach(Module me in MyModules){
Console.WriteLine("模块名:{0}",me.Name);
}

//程序集-包含->模块-包含->类型-包含->元素

Console.WriteLine("\n当前程序集的类型:\n");
Type[] AssTypes = currentAssembly.GetTypes();	//获取所有的类
foreach(Type sm in AssTypes){
Console.WriteLine("类型名:{0}",sm.Name);
Console.WriteLine("\n\t类型下的所有成员:");

//获取所有的类成员
MemberInfo[] mems = sm.GetMembers(
                                    BindingFlags.Instance
                                    |BindingFlags.Static
                                    |BindingFlags.Public
                                    |BindingFlags.NonPublic
                                    |BindingFlags.DeclaredOnly);
foreach(MemberInfo mem in mems){
Console.WriteLine("\t{0} {1}",mem.MemberType,mem);
}
}

Console.WriteLine("\n\n实例化Test类");
object[] parameters = new object[]{"反射创建的Test类对象……"};
object priobj = currentAssembly.CreateInstance("zuo_TestReflectionProject.Test",
                                            true,
                                            BindingFlags.Default,
                                            null,
                                            parameters,
                                            null,
                                            null);

//调用Test类中的方法
Type tt = typeof(Test);
tt.InvokeMember("show",BindingFlags.InvokeMethod,null,priobj,null);	//调用方法
}
}
#endregion

#region "应用程序区"
public class Test{	//创建一个带有私有构造函数的类
private string tname;
public Test(string t){
this.tname = t;

Console.WriteLine("是谁从沉睡中唤醒了我?");
}

public void show(){
Console.WriteLine(this.tname);
}
}

[SoftInfo("毁灭者","Ancore","3000-01-01",Memo="末日来临,万物皆灭!")]
[SoftInfo("修改人","Rich","2012-01-01",Memo="改进算法")]
[SoftInfo("创造人","左安坤","2011-09-27")]
public class People
{
private string firstName;
private string lastName;
private int age;
private string info;

public People():this(String.Empty,String.Empty,0){}
public People(string f,string l,int a){
this.firstName = f;
this.lastName = l;
this.age = a;
}

public string FirstName{
get{ return this.firstName; }
}
public string LastName{
get{ return this.lastName; }
}
public int Age{
get{ return this.age; }
}

public string Info{
get{ return this.info; }
set{ this.info = value; }
}

[SoftInfo("信息发送","沟通","2011-09-27",Memo="科技发展迅猛时期!")]
public void SendMessage(People pp,string s){
pp.Info = s;
Console.WriteLine("信息发送成功!");
}

public override string ToString()
{
return String.Format("姓:{0} 名:{1} 年龄:{2}",this.firstName,this.lastName,this.age);
}
}
#endregion

#region "特性区"
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,AllowMultiple=true)]
public class SoftInfoAttribute:Attribute
{
private string infoType;	//类型
private string author;	//作者
private DateTime dm;	//日期
private string memo;	//备注

public SoftInfoAttribute(string it,string au,string date){
this.infoType = it;
this.author = au;
this.dm = Convert.ToDateTime(date);
}

public string InfoType{
get{ return this.infoType; }
}
public string Author{
get{ return this.author; }
}
public DateTime Dm{
get{ return this.dm; }
}

public string Memo{
get{ return this.memo; }
set{ this.memo = value; }
}
}
#endregion
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: