本人转载:http://www.cnblogs.com/cuitsl/archive/2012/01/06/2314636.html
与反射的比较 首先能看到的是,dynamic与反射相比,执行相同操作所需的代码少的多。 如调用类Me中的GetName()方法。
class
Me {
public
string
Blog {
get
;
set
; }
public string GetName() { return " Zhenxing Zhou " ; }
}
public string GetName() { return " Zhenxing Zhou " ; }
}
用反射调用GetName()方法:
Assembly a
=
Assembly.GetExecutingAssembly();
object
instance
=
a.CreateInstance(
"
Xianfen.Net.TestDynamic.Me
"
); Type type
=
instance.GetType(); MethodInfo mi
=
type.GetMethod(
"
GetName
"
);
object
result
=
mi.Invoke(instance,
null
);
同样的dynamic调用:
dynamic myInfo
=
new
Me();
string
result
=
myInfo.GetName();
下面先举一个不用dynamic来实现反射的例子
class Program
{
static void Main(string[] args)
{
DynamicSample dynamicSample = new DynamicSample();
//通过反射得到DynamicSample的方法
var add = dynamicSample.GetType().GetMethod("Add");
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 100000; i++)
{
int re = (int)add.Invoke(dynamicSample, new object[] { 1, 2 });
}
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);//200毫秒左右
Console.Read();
}
}
public class DynamicSample
{
public string Name { get; set; }
public int Add(int a, int b)
{
return a + b;
}
}
试过几次,耗时基本在200毫秒左右,然后我们用dynamic来实现反射,看看性能如何
class Program
{
static void Main(string[] args)
{
dynamic dynamicSample = new DynamicSample();
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < 100000; i++)
{
int re = dynamicSample.Add(1, 2);
}
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);//50毫秒左右
Console.Read();
}
}
public class DynamicSample
{
public string Name { get; set; }
public int Add(int a, int b)
{
return a + b;
}
}
不仅代码变少了, 而且性能也提高了一个数量级,所有,大家能用动态属性实现反射的情况下建议都用动态属性来试下!