This repository has been archived by the owner on Apr 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 86
/
Program.cs
84 lines (73 loc) · 2.48 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Reflection;
using static System.Console;
#if DOTNETCORE
using System.Runtime.Loader;
#endif
namespace ClientApp
{
class Program
{
private const string CalculatorLibName = "CalculatorLib";
private const string CalculatorTypeName = "CalculatorLib.Calculator";
static void Main(string[] args)
{
if (args.Length != 1)
{
ShowUsage();
return;
}
ReflectionOld(args[0]);
ReflectionNew(args[0]);
}
private static void ShowUsage()
{
WriteLine($"Usage: {nameof(ClientApp)} path");
WriteLine();
WriteLine("Copy CalculatorLib.dll to an addin directory");
WriteLine("and pass the absolute path of this directory when starting the application to load the library");
}
private static void ReflectionNew(string addinPath)
{
double x = 3;
double y = 4;
dynamic calc = GetCalculator(addinPath);
double result = calc.Add(x, y);
WriteLine($"the result of {x} and {y} is {result}");
try
{
result = calc.Multiply(x, y);
}
catch (RuntimeBinderException ex)
{
WriteLine(ex);
}
}
private static void ReflectionOld(string addinPath)
{
double x = 3;
double y = 4;
object calc = GetCalculator(addinPath);
// previous to using the NuGet package System.Reflection.TypeExtensions
// object result = calc.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, calc, new object[] { x, y });
object result = calc.GetType().GetMethod("Add").Invoke(calc, new object[] { x, y });
WriteLine($"the result of {x} and {y} is {result}");
}
#if NET461
private static object GetCalculator(string addinPath)
{
Assembly assembly = Assembly.LoadFile(addinPath);
return assembly.CreateInstance(CalculatorTypeName);
}
#endif
#if DOTNETCORE
private static object GetCalculator(string addinPath)
{
Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(addinPath);
Type type = assembly.GetType(CalculatorTypeName);
return Activator.CreateInstance(type);
}
#endif
}
}