【问题标题】:C#/vb.net type mismatch looking up a constructor by reflection (Integer() vs System.Int32[])C#/vb.net 类型不匹配通过反射查找构造函数(Integer() vs System.Int32[])
【发布时间】:2010-01-29 22:00:28
【问题描述】:

我将 C# 代码中的类型名称和一些参数传递到用 VB 编写的导航框架中。导航框架在与使用 Type.GetConstructor(Types()) 传入的参数匹配的类型上查找构造函数。我正在寻找的构造函数需要一个整数数组——vb 中的 Integer()。但它得到一个 System.Int32 数组。我已经尝试过这个:

           System.Int32[] int32Array = IdList.ToArray();
            int[] intArray = new int[int32Array.Length];
            for (int i = 0; i < int32Array.Length; i++ )
            {
                intArray[i] = (int)int32Array[i];
            }

并且VB代码在另一端仍然看到System.Int32,这意味着它没有找到构造函数。

有什么见解吗?

【问题讨论】:

    标签: c# vb.net reflection interop constructor


    【解决方案1】:

    由于 C# intSystem.Int32 的语法糖,VB Integer 也是同一类型的语法糖。所以调用一个或另一个应该没有问题。

    不过,我会检查GetConstructor 方法返回的构造函数信息的参数类型。

    【讨论】:

      【解决方案2】:

      我猜你犯了我曾经犯过几次的同样的错误。

      当您调用 Type.GetConstructor(Type[]) 并构建一个类型数组时,我有时会生成一个类型对象数组,每个元素对应一个数组。

      让我解释一下。

      我有一个整数数组 (System.Int32),我想找到一个构造函数,它接受一个参数,该参数是一个整数数组。

      现在,在 C# 中,生成可传递给 GetConstructor 的类型数组的正确方法如下:

      Type[] types = new Type[] { typeof(Int32[]) };
      

      相反,我曾多次编写过这样的代码:

      Type[] types = (from v in arr select v.GetType()).ToArray();
      

      这是一个愚蠢的错误,但这种变化使 GetConstructor 寻找一个参数数量与我的数组中的值相同的构造函数。

      也许你也做过同样的事情?

      由于您实际上并未向我们展示调用反射的代码,但这只是推测。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-26
        • 2021-10-05
        • 2023-02-14
        • 2020-07-17
        • 1970-01-01
        相关资源
        最近更新 更多