mardi 7 mai 2019

When to use reflection instead of referencing an assembly

I created a dll in .NET Framework and use it now in another project. I found 2 ways to use my dll.

  1. By referencing the dll in my projects References and creating an instance

  2. By using Reflection

My DLL

namespace MathHelper
{
    public class Helper
    {
        public int add(int a, int b)
        {
            return a + b;
        }
    }
}

My Program

static void Main(string[] args)
        {
            //Using referenced dll in project
            Helper helper = new Helper();
            Console.WriteLine(helper.add(4,5));

            //Using Reflection
            Assembly assembly = Assembly.LoadFile(@"C:\Users\myUser\source\repos\TestMathHelper\TestMathHelper\bin\Debug\MathHelper.dll");
            Type type = assembly.GetType("MathHelper.Helper");
            object instance = Activator.CreateInstance(type);
            MethodInfo method = type.GetMethod("add");
            int result = (int)method.Invoke(instance, new object[] {4, 5});
            Console.WriteLine(result);

            Console.ReadKey();
        }

Both results worked and displayed 9.

Which method should I prefer? When should I use Reflection and when not? What is the advantage of Reflection?





Aucun commentaire:

Enregistrer un commentaire