在C#中反射的知识和Type类一起运用得很紧密。要说反射的运用方向,其实MVC就是利用了反射的知识。另外,如果你想做插件,反射的知识也是必不可少的。
Do类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestDll
{
public class Do
{
public string Name;
public event Action CallBack;
public Do()
{
}
public Do(String name , Int32 age)
{
this.Name = name;
this.Age = age;
}
public Int32 Age
{
get;
set;
}
public void DoSomeThing()
{
Console.WriteLine("Do.DoSomeThing(没有参数) 执行操作!");
}
public void DoSomeThing( string mask )
{
Console.WriteLine("Do.DoSomeThing(有参数) 执行操作!{0}", mask);
}
}
}关于控制台测试程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TestDll;
namespace TestReflect
{
class Program
{
static void Main(string[] args)
{
Assembly _assembly = Assembly.Load("TestDll");//加载程序集,并解析里面的matedata
Type _ty = _assembly.GetType("TestDll.Do");
//------实例化篇
object _ob = Activator.CreateInstance(_ty);//实例化一个对象 , 相当于New
object _obOverride = Activator.CreateInstance(_ty, "Ainy", 27);//实例化一个有参数的重载构造函数
///////////////////////////////////////////////////////////////////////////////
//这个_ob(Object)实际上就是Do
Do _testDo = _ob as Do;
_testDo.DoSomeThing();
///////////////////////////////////////////////////////////////////////////////
foreach(MethodInfo _methodItem in _ty.GetMethods())
{
Console.WriteLine("方法 : {0}" , _methodItem.Name);
}
//------方法篇
MethodInfo _hasParm = _ty.GetMethod("DoSomeThing", new Type[] { typeof(String) });//得到一个有String参数的方法 :DoSomeThing
//执行方法 : DoSomeThing(有参数的)
_hasParm.Invoke(_ob, new object[] { "Aonaufly" });
MethodInfo _noParm = _ty.GetMethod("DoSomeThing",new Type[]{});//获取不带参数的方法
_noParm.Invoke(_ob,new Object[]{});//执行无参数的方法
//------字段篇
FieldInfo _name = _ty.GetField("Name");
_name.SetValue(_ob, "Aonaufly1");
//------属性篇
PropertyInfo _age = _ty.GetProperty("Age");
_age.SetValue(_ob, 18);
Console.ReadKey();
}
}
}需要指出的问题:
1:类库的DLL,PDB文件要拷贝到程序集的Bin文件中。PDB文件可让程序进入调试。
2:Assembly.Load("TestDll")
实际是加载程序集(并解析matedata数据)。程序集即为:
3:_assembly.GetType("TestDll.Do")
家在Do类,以便调用
好了,看看执行结果:
本文出自 “Better_Power_Wisdom” 博客,请务必保留此出处http://aonaufly.blog.51cto.com/3554853/1860664
原文:http://aonaufly.blog.51cto.com/3554853/1860664