예제 #1
0
 /// <summary>
 /// Creates a new instance of the safe constructor wrapper.
 /// </summary>
 /// <param name="constructor">Constructor to wrap.</param>
 public SafeConstructor(ConstructorInfo constructor)
 {
     this.constructorInfo = constructor;
     if (constructor.IsPublic &&
         ReflectionUtils.IsTypeVisible(constructor.DeclaringType, DynamicReflectionManager.ASSEMBLY_NAME))
     {
         this.dynamicConstructor = DynamicConstructor.Create(constructor);
         this.isOptimized        = true;
     }
 }
        public void TestConstructors()
        {
            IDynamicConstructor newInventor = DynamicConstructor.Create(
                typeof(Inventor).GetConstructor(new Type[] { typeof(string), typeof(DateTime), typeof(string) }));
            Inventor ana = (Inventor)newInventor.Invoke(new object[] { "Ana Maria Seovic", new DateTime(2004, 8, 14), "Serbian" });

            Assert.AreEqual("Ana Maria Seovic", ana.Name);

            IDynamicConstructor newDate = DynamicConstructor.Create(
                typeof(DateTime).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int) }));

            Assert.AreEqual(DateTime.Today, newDate.Invoke(new object[] { DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day }));
        }
        //[Test]
        public void PerformanceTests()
        {
            int    n = 10000000;
            object x = null;

            // new Inventor()
            start = DateTime.Now;
            for (int i = 0; i < n; i++)
            {
                x = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian");
            }
            stop = DateTime.Now;
            PrintTest("new Inventor() (direct)", n, Elapsed);

            start = DateTime.Now;
            IDynamicConstructor newInventor = DynamicConstructor.Create(
                typeof(Inventor).GetConstructor(new Type[] { typeof(string), typeof(DateTime), typeof(string) }));

            for (int i = 0; i < n; i++)
            {
                object[] args = new object[] { "Nikola Tesla", new DateTime(1856, 7, 9), "Serbian" };
                x = newInventor.Invoke(args);
            }
            stop = DateTime.Now;
            PrintTest("new Inventor() (dynamic reflection)", n, Elapsed);

            start = DateTime.Now;
            ConstructorInfo newInventorCi =
                typeof(Inventor).GetConstructor(new Type[] { typeof(string), typeof(DateTime), typeof(string) });

            for (int i = 0; i < n; i++)
            {
                object[] args = new object[] { "Nikola Tesla", new DateTime(1856, 7, 9), "Serbian" };
                x = newInventorCi.Invoke(args);
            }
            stop = DateTime.Now;
            PrintTest("new Inventor() (standard reflection)", n, Elapsed);
        }