由于 ReflectionTypeLoadException,无法从程序集中检索 TypeInfo

Cannot retrieve TypeInfo(s) from assembly due to ReflectionTypeLoadException

我试图通过在 C# 中使用 System.Reflection 将所有定义的类型检索到 .NET 程序集中。首先我加载程序集:

var assembly = Assembly.LoadFrom("C:\...\myassembly.dll");

然后我尝试获取程序集中类型的所有 TypeInfo

try {
    var types = assembly.DefinedTypes;
}
catch(ReflectionTypeLoadException ex)
{
    var errorMessage = new StringBuilder();
    errorMessage.AppendLine($"Error loading defined types in assembly {this.assembly.FullName}. Found {ex.LoaderExceptions.Length} errors:");

    foreach (var innerException in ex.LoaderExceptions)
    {
        errorMessage.AppendLine($"{innerException.GetType().Name} - {innerException.HResult}: {innerException.Message}");
    }

    throw new InvalidOperationException(errorMessage.ToString(), ex);
}

失败

我遇到的失败是 ReflectionTypeLoadException,我遇到了 ex.LoaderExceptions 很多异常,例如:

-2146233054: Could not load type 'MyType' from assembly 'myassembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the method '.ctor' has no implementation (no RVA)

关于反射上下文

我发现 this question 解决了同样的问题,建议之一是使用:

var assembly = Assembly.ReflectionOnlyLoadFrom("C:\...\myassembly.dll");

这看起来很合乎逻辑。但是它没有用。

我的问题

我的问题很简单:如何通过忽略程序集中未完全定义或缺少实现的类型的错误,从可用类型中获取所有 TypeInfo

我知道 ex.Types 会给我一个我可以从异常中使用的类型列表,但这会给我 System.Type 而不是 System.Reflection.TypeInfo。我想要后者,因为它有更多关于我需要的类型的信息。我链接的问题没有处理这个问题!

您可以通过调用 IntrospectionExtensions.GetTypeInfo 扩展方法从 Type 对象中获取 TypeInfo。所以它应该像这样简单:

var typeInfo = ex.Types.Select(IntrospectionExtensions.GetTypeInfo).ToArray();