如何反映已加载的程序集?

发布于 2024-12-11 04:59:58 字数 328 浏览 0 评论 0原文

我的解决方案中有 2 个项目。 Project1UI引用Project2Reports

Project1UI:
  MainForm.cs

Project2Reports:
  BaseReport.cs  // all classes below inherit from it
  Report1.cs
  Report2.cs
  Report3.cs

从Project1UI中,如何找到继承自BaseReport的所有类? project1UI 已经引用了第二个程序集 - 有没有办法无需手动加载第二个程序集(例如 Assembly.Load),因为它已经加载了。

I have 2 projects in the solution. Project1UI references Project2Reports

Project1UI:
  MainForm.cs

Project2Reports:
  BaseReport.cs  // all classes below inherit from it
  Report1.cs
  Report2.cs
  Report3.cs

From Project1UI, how can I find all the classes that inherit from BaseReport? The project1UI already references the 2nd assembly - is there a way to do it without manually loading the 2nd assembly manually (e.g. Assembly.Load) since it's already loaded.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

私野 2024-12-18 04:59:58

您必须处理程序集中的所有类型并查找实现它的类型。

你可以使用类似的东西(现在手写,它可能包含错误)。

foreach (Type type in Assembly.GetAssembly(typeof(BaseReport)).GetTypes())
{
    if (type != typeof(BaseReport) && typeof(BaseReport).IsAssignableFrom(type))
    {
        // we found a type, we can store it somewhere, for example, in a list and our list in a static readonly field for fast lookup in the future.
        myreports.Add(type);
    }
}

您还可以处理所有加载的程序集。

然而,这并不是最好的方法,它很复杂、很晦涩并且很难理解。
我将使用一个简单的工厂类,它将根据要求为您提供报告的实例,当您添加报告时,通过简单的 .Add 调用添加它。

You have to process all the types in the assembly and look for the types that implement it.

You can use something like that (written by hand right now, it may contains errors).

foreach (Type type in Assembly.GetAssembly(typeof(BaseReport)).GetTypes())
{
    if (type != typeof(BaseReport) && typeof(BaseReport).IsAssignableFrom(type))
    {
        // we found a type, we can store it somewhere, for example, in a list and our list in a static readonly field for fast lookup in the future.
        myreports.Add(type);
    }
}

You can also process all the loaded assemblies.

This however is not the best way to do that, is complicated, quite obscure and quite hard to understand.
I would use a simple factory class that will give you the instance of your report as requested, when you add a report, add it through a simple .Add call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文