简体   繁体   English

VB6和C#的COM互操作

[英]COM Interop with VB6 and C#

I'm writing a C# COM object that will be used by a VB 6 program. 我正在编写将由VB 6程序使用的C#COM对象。 That shouldn't be much of a problem, however, the VB6 call to the COM object passes in a VB Control (in this case a TextBox). 但这不是什么大问题,但是,对COM对象的VB6调用传入了VB控件(在这种情况下为TextBox)。 The program expects the COM object to alter the Text property of the control. 该程序希望COM对象更改控件的Text属性。 Unfortunately, I have to stick to this interface as I'm dealing with someone elses legacy code. 不幸的是,我在处理其他人的遗留代码时必须坚持使用该界面。

How can I set the property for the passed in TextBox? 如何设置在TextBox中传递的属性? Do I simply create an interface with a Text property and cast input to that interface? 我是否只是使用Text属性创建一个接口并将input转换为该接口? Is this even possible? 这有可能吗?

Please let me know if I need to clarify. 如果需要澄清,请告诉我。 Note: I intended to leave out the COM declarations in the following code. 注意:我打算在以下代码中省略COM声明。

// C# COM Object Interface
public interface IObj
{
    // This function must receive the argument of type object.
    void Test(object input);
}

// C# COM Object Implementation
public class Obj : IOjb
{
    // A VB6 TextBox is passed into here,
    // expecting a change to the Text property.
    public void Test(object input)
    {
        // INSERT NECESSARY CODE HERE

        input.Text = "arbitrary string";
    }
}


// VB 6
comObject.Test (txtBox)

您应该将用于更新文本框的代码和任何其他特定于UI的代码放入VB6 COM对象中,并将任何非UI代码交给C#类,这样就不必在C#中处理VB6 UI控件。

Are you using .Net 4.0? 您正在使用.Net 4.0吗?

You could try using the new dynamic language features: 您可以尝试使用新的动态语言功能:

public void Test(object input)
{
    dynamic textBox = input;
    //Assuming there is a property named Text at runtime
    textBox.Text = "arbitrary string";
}

This should do the equivalent of late binding in COM. 这应该等效于COM中的后期绑定。

You might also try using dynamic in your method declaration. 您也可以尝试在方法声明中使用dynamic。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM