如何从 C# 中的 DLL 获取类型列表?

发布于 2024-09-14 19:23:41 字数 593 浏览 1 评论 0原文

我想将 C# 应用程序指向 DLL,并获取该 DLL 中定义的类型列表。 到目前为止,我所看到的表面上看起来很正确,但给出了下面指出的错误。

using System.Reflection;

...

static void Main(string[] args)
{
    Assembly SampleAssembly;
    SampleAssembly = Assembly.LoadFrom("C:\\MyAssembly.dll"); //error happens here

    foreach (Type tp in SampleAssembly.GetTypes())
    {
        Console.WriteLine(tp.Name);
    }
}

/*
This will give me:
Unable to load one or more of the requested types.
Retrieve the LoaderExceptions property for more information.

I wish it would give me something like this:
MyClass1
MyClass2
MyClass3
*/

I'd like to point a C# application at a DLL and get a list of the types defined in that DLL.
What I have so far looks right on the surface, but is giving the error indicated below.

using System.Reflection;

...

static void Main(string[] args)
{
    Assembly SampleAssembly;
    SampleAssembly = Assembly.LoadFrom("C:\\MyAssembly.dll"); //error happens here

    foreach (Type tp in SampleAssembly.GetTypes())
    {
        Console.WriteLine(tp.Name);
    }
}

/*
This will give me:
Unable to load one or more of the requested types.
Retrieve the LoaderExceptions property for more information.

I wish it would give me something like this:
MyClass1
MyClass2
MyClass3
*/

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

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

发布评论

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

评论(2

浅听莫相离 2024-09-21 19:23:41

使用 ReflectionOnlyLoad 而不是直接加载,以防止运行时尝试运行目标程序集中的任何代码

Use ReflectionOnlyLoad instead of a straight load to prevent the runtime from attempting to run any code in the target assembly

别在捏我脸啦 2024-09-21 19:23:41

抛出 ReflectionTypeLoadException 是因为您的一种类型在静态初始化期间抛出异常。如果方法/属性/字段签名依赖于不可用的类型,则可能会发生这种情况。我建议您捕获该异常并按照建议检查异常的 LoaderExceptions 属性的内容。

The ReflectionTypeLoadException is being thrown because one of your types is throwing an exception during static initialization. This can happen if the method/property/field signatures depend on a Type that is not available. I recommend you catch for that exception and inspect the contents of the exception's LoaderExceptions property as suggested.

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