比如说,我有很多计算数字平方根的方法。
一位开发人员给了我他自己的.dll (maths1.dll),另一位也给了我他的 (maths2.dll),也许还有第三个 (maths3.dll)。
它们都包含相同的类,实现相同的接口。
汇编 1 Maths1.dll
public class Maths : IMaths {
public static string Author = "Author1";
public static SquareRoot(int number) {
// Implementation method 1
}
}
汇编 2 Maths2.dll
public class Maths : IMaths {
public static string Author = "Author2";
public static SquareRoot(int number) {
// Implementation method 2
}
}
等等等等
而且我有一个控制台应用程序,它必须在运行时动态地了解所有 dll。
在代码中查找 .dll 文件是不可取的。
// DON'T WANT THIS
DirectoryInfo di = new DirectoryInfo("bin");
FileInfo[] fi = di.GetFiles("*.dll");
我的想法是使用自定义配置部分从app.config文件管理它们。
<configuration>
<configSections>
<section name="MathsLibraries" type="MyMathsLibrariesSectionClass, ApplicationAssembly" />
</configSections>
<MathsLibraries>
<Library author="Author1" type="MathsClass, Maths1Assembly" /><!-- Maths1.dll -->
<Library author="Author2" type="MathsClass, Maths2Assembly" /><!-- Maths2.dll -->
<Library author="Author3" type="MathsClass, Maths3Assembly" /><!-- Maths3.dll -->
</MathsLibraries>
</configuration>
考虑到我将手动将库文件Maths1.dll复制到我的应用程序的bin文件夹中。然后,我唯一要做的就是在MathsLibraries部分的app.config文件中添加一行。
我需要控制台应用程序Main的示例代码,向用户展示所有动态链接的 .dll 并允许他使用所选库计算数字的平方根。
// NOT WORKING CODE, JUST IDEA OF WHAT IS NEEDED
public static void Main(string[] args) {
// Show the user the linked libraries
MathsLibraries libs = MathsLibraries.GetSection();
Console.WriteLine("Available libraries:");
foreach (MathLibrary lib in libs.Libraries) {
Console.WriteLine(lib.Author);
}
// Ask for the library to use
Console.Write("Which do you want to use?");
selected_option = Console.Read();
IMaths selected_library;
// since we don't know wich class would be,
// declare a variable using the interface we know they al implement.
// Assign the right class to the variable
if (selected_option == '1') {
selected_library = Assembly1.Maths;
} else if (selected_option == '2') {
selected_library = Assembly2.Maths;
}
// other options...
// Invoke the SquareRoot method of the dynamically loaded class
float sqr_result = selected_library.SquareRoot(100);
Console.WriteLine("Result is {0}", sqr_result);
Console.WriteLine("Press Enter key to exit");
Console.Read();
}
拜托,任何人都可以帮助我完成从 app.config 加载程序集的任务。
详细的代码将不胜感激。
谢谢!