目前我正在开发一个 C# 项目,我必须在其中实现反射。我创建了一个带有 GUI 的 WPF 应用程序。该 GUI 包含一个
组合框,其中包含实现特定接口的所有类名。具有显示的类名的类位于同一解决方案中。
组合框旁边有一个按钮,用于刷新组合框中的内容。但是,当我运行我的应用程序时,修改实现该接口的类名,并且
单击该刷新按钮,更改不会显示在组合框中。例如,当我更改类名时,它应该显示新的类名而不是旧的类名。
我已经提取了项目的这一部分,以便在空控制台应用程序中对其进行测试。这里我有一个由类实现的接口
快速排序算法、动态排序算法和合并排序算法。接下来,我在主类中编写了以下直接代码。
public static List<string> AlgoList = new List<string>();
static void Main(string[] args) {
RefreshAlgorithms();
Print();
Console.WriteLine("\nChange a classname and press a key \n");
Console.ReadKey();
Print();
Console.WriteLine("\nPress a key to exit the program \n");
Console.ReadKey();
}
private static void RefreshAlgorithms() {
AlgoList.Clear();
Type AlgorithmTypes = typeof(IAlgorithms);
foreach (var type in Assembly.GetCallingAssembly().GetTypes()) {
if (AlgorithmTypes.IsAssignableFrom(type) && (type != AlgorithmTypes)) {
AlgoList.Add(type.Name);
}
}
}
private static void Print() {
Console.WriteLine("Algorithm classes:");
foreach (var Algo in AlgoList) {
Console.WriteLine(Algo);
}
}
当我运行应用程序时,会看到打印的类名 QuickSortAlgorithm、DynamicSortAlgorithm 和 MergeSortAlgorithm。但是,如果我更改名称,例如,
QuickSortAlgorithm 类到 QuickSortAlgorithmmmmm 我希望一旦按下某个键它就会打印 QuickSortAlgorithmmmm。然而事实并非如此,名字也并非如此
QuickSortAlgorithm 仍在显示。
我感觉我忽略了反思概念中的一些东西。构建解决方案后还可以这样做吗?如果我理解正确的话,这个概念使得在运行时实现更改成为可能。我知道
它会使我的应用程序变慢,但我真的很渴望了解更多有关这个概念的信息。如果有人能解释我做错了什么,我会很高兴。
不幸的是,这不起作用。当您的程序集被加载时,它将保持原样加载,更改仅在您重新启动应用程序时应用。
如果您使用 .NET Framework,您可以创建一个新的 AppDomain 并将程序集加载到此 AppDomain 中。完成后,您可以卸载 AppDomain 及其程序集。您可以在正在运行的应用程序中多次执行此操作。
void RefreshAlgorithms()
{
var appDomain = AppDomain.CreateDomain("TempDomain");
appDomain.Load(YourAssembly);
appDomain.DoCallback(Inspect);
AppDomain.Unload(appDomain);
}
void Inspect()
{
// This runs in the new appdomain where you can inspect your classes
}
但要小心,因为使用 AppDomains 有一些注意事项,例如与 AppDomain 通信时需要使用远程处理。
据我所知,在.NET Core中没有这样的方法可用
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)