.net的反射 真可谓让人忧让人喜,有了反射 在.net中工厂模式更容易实现而且耦合性更低,但是反射对性能的消耗也是不可忽视的。
测试程序:(需要被反射而获得的类)
using System; using Edot.Interface; namespace Edot.TestReflection { public class A : IA { public A() { } public void Print() { Console.WriteLine( "The A Class" ); } }; } |
接口:
using System; namespace Edot.Interface { public interface IA { void Print(); } } |
用反射创建类的类:
using System; using System.Reflection; using Edot.Interface; namespace Edot.Create { public class Create { private static IA _ia = null; public Create() { } public static IA CreateA() { if ( _ia == null ) { Type[] type = new Type[]{}; ConstructorInfo ctor = Assembly.LoadFrom( "A.dll" ).GetType( "Edot.TestReflection.A" ).GetConstructor( type ); _ia = ctor.Invoke( type ) as IA; } return _ia; } }; } |
测试类:
using System; using Edot.Interface; namespace Edot.Test { public class Test { public Test() { } public static void Main() { Console.WriteLine( DateTime.Now.ToString( "mm:ss:fffff" ) ); IA ia = Edot.Create.Create.CreateA(); ia.Print(); Console.WriteLine( DateTime.Now.ToString( "mm:ss:fffff" ) ); Console.ReadLine(); } }; } |
最后获得的结果:
从结果我们可以看出,反射的性能并不是被那些书上说的一无是处。也许这个程序太小,看不出。但是,如果我们使用一些性能优化的方法,性能可能进一步提高。
下面我们对不使用反射的情况测试一下,修改使用反射创建类的类。
为(不使用反射):
using System; using System.Reflection; using Edot.Interface; using Edot.TestReflection; namespace Edot.Create { public class Create { private static IA _ia = null; public Create() { } public static IA CreateA() { if ( _ia == null ) { _ia = new A(); } return _ia; } }; } |
结果如下图:
看到结果,你也许很惊讶,反射对性能的消耗并不是特别大阿。而且使用反射,程序耦合度几乎降到 “0”是几乎阿。呵呵···
我觉得为使程序的扩展性好,这么一点点损耗是值得的,而且我们还可以使用很多技术来优化反射,比如缓存。
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。