【问题标题】:System.BadImageFormatException when trying to resolve constructor of System.Collections.Generic.GenericComparer`1尝试解析 System.Collections.Generic.GenericComparer`1 的构造函数时出现 System.BadImageFormatException
【发布时间】:2017-05-15 09:16:45
【问题描述】:

我对以下代码有疑问:

var type1 = typeof(object);
var type2 = type1.Module.GetType("System.Collections.Generic.GenericComparer`1");
var constr = type2.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
var byteArray = constr.GetMethodBody().GetILAsByteArray();
var result = type2.Module.ResolveMethod(BitConverter.ToInt32(byteArray, 2));

每次我执行它都会给我以下错误:

An exception of type 'System.BadImageFormatException' occurred in mscorlib.dll and wasn't handled before a managed/native boundary
Additional information: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

但是,如果不这样做

var type2 = type1.Module.GetType("System.Collections.Generic.GenericComparer`1");

我使用它的基类

var type2 = type1.Module.GetType("System.Collections.Generic.Comparer`1");

然后“ResolveMethod”返回OK。

有人知道为什么这个类不能被“解决”吗?

谢谢!

【问题讨论】:

  • 我尝试在 32 位和 64 位中构建应用程序,但都给出了错误。我认为这与此无关。
  • 可能是因为GenericComparer 是内部的?
  • 不这么认为..我已经尝试过 System.Collections.StructuralComparer,它也是内部的,它可以工作..

标签: .net reflection comexception badimageformatexception


【解决方案1】:

它确实说这可能是由于缺乏通用上下文。您可以看到它们的基类的差异,因为如果您查看 System.Collections.Generic.GenericComparer`1 派生自它的类型,则至少在我检查它时不是来自您所说的基类。它甚至没有全名。它还有一个 GenericTypeArgument[1] 而 t1 在我下面的示例中没有。

        var t1 = Type.GetType("System.Collections.Generic.Comparer`1");
        var t2 = Type.GetType("System.Collections.Generic.GenericComparer`1").BaseType;
        bool assignable = t1.IsAssignableFrom(t2);

【讨论】:

  • 这很有趣..我用 dotPeek 看了一下,GenericComparer'1 继承自 Comparer'1 internal class GenericComparer<T> : Comparer<T> where T : IComparable<T>
【解决方案2】:

我在问是否有解决方案,因为我正在使用 DeepCloner 克隆一些对象,其中一些具有 IEnumerable 的属性,它们的值是包含 order by 的表达式或它执行查询到数据库。

当我尝试克隆此类对象时,DeepCloner 在尝试解析 System.Collections.Generic.GenericComparer'1 的构造函数或尝试解析查询数据库所需的其他方法时会给出该异常。

这是vb.net中的一个例子:

    Public Class cls1
        Public Property prop2 As Integer
    End Class


    Public Class cls0
        Public Property prop1 As IEnumerable(Of cls1)
    End Class

    Private Sub doClone()
        Dim ob1 = New cls0()
        Dim source = New List(Of cls1)
        For i = 0 To 10 - 1
            source.Add(New cls1() With {.prop2 = i})
        Next
        ob1.prop1 = (From a In source Where a.prop2 < 5 Order By a.prop2 Select a)
        ob1.DeepClone()
    End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2021-12-03
    相关资源
    最近更新 更多