This article is currently in the process of being translated into Ukrainian (~19% done).


Instantiating a class

До цього ми працювали з типами або об'єктами .NET, дял яких вже були створені екземпляри класів. Але з рефлексією ми можемо насправді створити екземпляр під час виконання, знаючи назву класу, екземпляр якого ми можемо створити. Існує декілька підходів до виконання даної задачі, але я надаю перевагу отриманню посилання на конструктор, яких хочу використати, викликаючи його, а потім використати тип, що повертається, як екземпляр класу. Ось приклад цього. Код спочатку, потім я поясню це все.

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTest
    class Program
        static void Main(string[] args)
            Type testType = typeof(TestClass);
            ConstructorInfo ctor = testType.GetConstructor(System.Type.EmptyTypes);
            if(ctor != null)
                object instance = ctor.Invoke(null);
                MethodInfo methodInfo = testType.GetMethod("TestMethod");
                Console.WriteLine(methodInfo.Invoke(instance, new object[] { 10 }));

    public class TestClass
        private int testValue = 42;

        public int TestMethod(int numberToAdd)
            return this.testValue + numberToAdd;

I have defined a simple class for testing this, called TestClass. It simply contains a private field and a public method. The method returns the value of the private property, with the value of the parameter added to it. Now, what we want is to create a new instance of this TestClass, call the TestMethod and output the result to the console.

In this example, we have the luxury of being able to use the typeof() directly on the TestClass, but at some point, you may have to do it solely by using the name of the desired class. In that case, you can get a reference to it through the assembly where it is declared, as demonstrated in the chapter about Type.

So, with a Type reference to the class, we ask for the default constructor by using the GetConstructor() method, passing System.Type.EmptyTypes as a parameter. In case we wanted a specific constructor, we would have to provide an array of Type's, each defining which parameter the constructor we were looking for, would take.

Once we have a reference to the constructor, we simply call the Invoke() method to create a new instance of the TestClass class. We pass null as the parameter to Invoke(), since we're not looking to specify any parameters. We use the GetMethod(), along with the name of the method we want, to get the TestMethod() function, and then we once again use the magic of the Invoke() method to call this function. This time we need to specify a parameter, in the form of an array of objects. We do that on-the-fly, specifying the number 10 as the only parameter we need, and we then output the result of the method invocation. All of this through the magic of Reflection!

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!