mardi 24 novembre 2015

Reflection C# Activator returning a null value

Please I don't know what I am doing wrong, when I run this code, I get an exception: Value cannot be null.... When I run it in debug mode, I see that "calculatorInstance" variable is null. Please help me out.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace ReflectionWithLateBinding
{
    public class Program
    {
        static void Main()
        {
            //load the current executing assembly
            Assembly executingAssembly = Assembly.GetExecutingAssembly();

            //load and instantiate the class dynamically at runtime - "Calculator class"
            Type calculatorType = executingAssembly.GetType("ReflectionWithLateBinding.Calculator");


            //Create an instance of the type --"Calculator class"
            object calculatorInstance = Activator.CreateInstance(calculatorType);

            //Get the info of the method to be executed in the class
            MethodInfo sumArrayMethod = calculatorType.GetMethod("SumNumbers");

            object[] arrayParams = new object[2];

            arrayParams[0] = 5;
            arrayParams[1] = 8;
            int sum;
            sum = (int)sumArrayMethod.Invoke(calculatorInstance, arrayParams);

            Console.WriteLine("Sum = {0}",  sum);

            Console.ReadLine();

        }



        public class Calculator
        {
            public int SumNumbers(int input1, int input2)
            {
                return input1 + input2;
            }
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire