反射大家都不陌生,在NET4中引入了dynamic关键字,使用它可以简化后期绑定,这里我就不废话连篇了,直接上代码,直白的代码是最简单明了的诠释:
1.我们构建一个 Class Libary 命名为SimpleCaculator
2.在类库中构建类:
namespace SimpleCaculator
{
public class SimpleMath
{
public int Add(int a, int b)
{
return a + b;
}
public int Sub(int a, int b)
{
return a - b;
}
}
{
public class SimpleMath
{
public int Add(int a, int b)
{
return a + b;
}
public int Sub(int a, int b)
{
return a - b;
}
}
}
3.构建Console Application 命名为:Dynamic-Reflect
4.编译SimpleCaculator 并且复制到Dynamic-Reflect项目的\bing\Debug目录下(如果你是Release构建,则复制到\bing\Release目录下)
5. Dynamic-Reflect的调用代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Dynamic_Reflect
{
class Program
{
static void Main(string[] args)
{
OriginalReflection();
ReflectWithDynamic();
}
private static void OriginalReflection()
{
Assembly asm = Assembly.Load("SimpleCaculator");
try
{
Type simpleMath = asm.GetType("SimpleCaculator.SimpleMath");
object obj = Activator.CreateInstance(simpleMath);
MethodInfo mi = simpleMath.GetMethod("Add");
object[] args = { 20, 30 };
Console.WriteLine("The Result of {0} + {1} is: {2} ", 20, 30, mi.Invoke(obj,args));
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void ReflectWithDynamic()
{
Assembly asm = Assembly.Load("SimpleCaculator");
try
{
Type simpleMath = asm.GetType("SimpleCaculator.SimpleMath");
dynamic obj = Activator.CreateInstance(simpleMath);
Console.WriteLine("The Result of {0} + {1} is: {2} ", 20, 30, obj.Add(20, 30));
Console.ReadKey();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Dynamic_Reflect
{
class Program
{
static void Main(string[] args)
{
OriginalReflection();
ReflectWithDynamic();
}
private static void OriginalReflection()
{
Assembly asm = Assembly.Load("SimpleCaculator");
try
{
Type simpleMath = asm.GetType("SimpleCaculator.SimpleMath");
object obj = Activator.CreateInstance(simpleMath);
MethodInfo mi = simpleMath.GetMethod("Add");
object[] args = { 20, 30 };
Console.WriteLine("The Result of {0} + {1} is: {2} ", 20, 30, mi.Invoke(obj,args));
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void ReflectWithDynamic()
{
Assembly asm = Assembly.Load("SimpleCaculator");
try
{
Type simpleMath = asm.GetType("SimpleCaculator.SimpleMath");
dynamic obj = Activator.CreateInstance(simpleMath);
Console.WriteLine("The Result of {0} + {1} is: {2} ", 20, 30, obj.Add(20, 30));
Console.ReadKey();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}