尝试使用 COM 互操作从 C# 库在 vb6 中附加对象时,获取“无法将“字段”转换为“字段”类型同一类”

问题描述

我有一个由旧版 vb6 代码使用的 C# 库。这对大多数情况都非常有效,除非我遇到了附加对象的问题。

部分地,我试图模拟一些访问数据库函数调用并将它们重定向到不同的数据库解决方案。但这与我遇到的问题不太相关,只是一些背景。

我有一个与这个非常相似的对象和类;使用 Append 也做同样的事情。代码的不同之处仅在于它不是使用的“对象”而是固定类型。我尝试这样做,因为 COM 标准不支持泛型。

任何想法或帮助都会非常有帮助。

在 vb6 中

Dim fld As Field
Set fld = new Field
NewTd.Fields.Append fld     'gives an error that Field can't be cast to type Field. 

C#

字段:

 [Guid("2515418d-04af-484e-bb3b-fe53a6121f73")]
 [ClassInterface(ClassInterfaceType.None)]
 public class Field : IField
 {
     public string Name { get; set; }
     public string Value { get; set; }

     public int Type { get; set; } //private int TypePV;
     // 3 more public ints.


     enum FieldType
     {
         // different field types.
     }

---

 [Guid("fd362bff-da4e-4419-a379-1ed84ff74f1b")]
 public interface IField
 {
        string Name { get; set; }
        string Value { get; set; }
        int Type { get; set; }
        // three more ints.

 }

Append 的定义位置。

[Guid("0cf3c33f-8ca8-4a5b-8382-d1612558fcad")]
[ClassInterface(ClassInterfaceType.None)]
public class FieldsO : IFieldsO
{
    public object obj;
    public FieldsO(object cobj)
    {
        obj = cobj;
    }

    public object this[string param]
    {
        get 
        {
            if (obj.GetType() == typeof(Recordset))
                return ((Recordset)obj)[param];
            if (obj.GetType() == typeof(TableDef))
                return ((TableDef)obj)[param];
            return null;
        }
        set 
        { 
            if (obj.GetType() == typeof(Recordset))
                ((Recordset)obj)[param] = value; 
            if (obj.GetType() == typeof(TableDef))
                ((TableDef)obj)[param] = (IField)value; 
        }
    }

    public void Append(Field io) {
        if (obj.GetType() == typeof(TableDef)) {
            if (!((TableDef)obj)._Fields.ContainsKey(io.Name))
                ((TableDef)obj)._Fields.Add(io.Name,io);
        }
    }

    public int Count() {
        if (obj.GetType() == typeof(Recordset))
            return ((Recordset)obj).dt.Columns.Count;
        if (obj.GetType() == typeof(TableDef))
            return ((TableDef)obj)._Fields.Count;
        return -1;
    }
}

---

 [Guid("fe528160-1505-448e-bb9c-8ccfd9e3643d")]
 public interface IFieldsO
    {
       object this[string param] { get; set; }
       int Count();
       void Append(Field io);
    }

解决方法

答案很简单。 我更改了代码以期望在 Append 上有一个“对象”,发现 vb6 错误代码更具体。它在代码的来源方面存在问题。从那里我所做的就是制作项目(将其编译为可执行文件)并且一切正常,没有例外,什么都没有。

在处理奇怪错误时,解决方案通常似乎是不依赖于 vb6 IDE。