Como instanciar a classe em uma montagem usando Reflexão com C # /. NET?
Tenho esta biblioteca para compilada em calc.dl
namespace MyClass
{
public class Calculator
{
public int Value1 {get; set;}
public int Value2 {get; set;}
public Calculator()
{
Value1 = 100;
Value2 = 200;
}
public int Add(int val1, int val2)
{
Value1 = val1; Value2 = val2;
return Value1 + Value2;
}
}
}
Eu quero instanciar a classe Calculate sem vincular à calc.dll. C # pode fazer isso? Eu vim com esse código, mas não sei como instanciar oCalculator
classe
using System;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
namespace EX
{
public class Code
{
public static void Test()
{
string path = Directory.GetCurrentDirectory();
string target = Path.Combine(path, @"./myclass.dll");
Assembly asm = Assembly.LoadFrom(target);
Calculator h = new Calculator(); // <-- ???
Type type = h.GetType();
MethodInfo m = type.GetMethod("Add");
int res = (int) m.Invoke(h, param);
Console.WriteLine("{0}", res);
}
public static void Main()
{
Test();
}
}
}
ADDEDTenho duas soluções, uma é da Bala R
var param = new object[] {100, 200};
string path = Directory.GetCurrentDirectory();
string target = Path.Combine(path, @"./myclass.dll");
Assembly asm = Assembly.LoadFrom(target);
Type calc = asm.GetType("MyClass.Calculator");
object h = Activator.CreateInstance(calc);
MethodInfo m = calc.GetMethod("Add");
int res = (int) m.Invoke(h, param);
Console.WriteLine("{0}", res);
E este é do agente-j
string path = Directory.GetCurrentDirectory();
string target = Path.Combine(path, @"./myclass.dll");
Assembly asm = Assembly.LoadFrom(target);
Type type = asm.GetType("MyClass.Calculator");
ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes);
object calc = ctor.Invoke(null);
MethodInfo m = type.GetMethod("Add");
var param = new object[] {100, 200};
int res = (int) m.Invoke(calc, param);
Console.WriteLine("{0}", res);
Ambos estão funcionando, mas eu prefiro a solução da Bala, pois é mais curta e obtémobject h
atravésCreateInstance
é mais intutivo do que obter construtor para obterobject h(calc)
.