簡體   English   中英

如何在C#中聲明經典COM接口IBindCtx?

[英]How to declare Classic COM Interface IBindCtx in C#?

我目前在C#和COM接口周圍閑逛。 C#中的COM文檔很少,因為C#緊隨COM之后(也許我們可以解決)。 我發現C#編譯器可以提供有用的錯誤消息 可以從錯誤消息中讀取方法簽名的C#語法版本,然后將其添加到您的類中。 這適用於IAdviseSink,但不適用於IBindCtx。

我對最后一個方法RevokeObjectParam(string a)遇到錯誤,C ++中的語法為HRESULT RevokeObjectParam( [in] LPOLESTR pszKey ); LPOLESTR是一個以2 LPOLESTR的以null終止的字符串,因此可以使用[MarshalAs(UnmanagedType.LPWStr)] 但是沒有,我收到錯誤消息

     * Class1.cs(25,14,25,40): error CS0539: 'IBindCtx.RevokeObjectParam' in explicit interface declaration is not a member of interface
     * Class1.cs(6,18,6,24): error CS0535: 'ComInterfacesInCSharp.Class1' does not implement interface member 'System.Runtime.InteropServices.ComTypes.IBindCtx.RevokeObjectParam(string)'

那么,如何修改此方法簽名以進行修復? 下面是可復制到Visual Studio中的完整代碼(創建類庫項目)。

using System.Runtime.InteropServices.ComTypes;
using System.Runtime.InteropServices;

namespace ComInterfacesInCSharp
{
    public class Class1 : System.Runtime.InteropServices.ComTypes.IBindCtx 
    {
        void IBindCtx.RegisterObjectBound(object obj) { }
        void IBindCtx.RevokeObjectBound(object obj) { }
        void IBindCtx.ReleaseBoundObjects() { }
        void IBindCtx.SetBindOptions(ref System.Runtime.InteropServices.ComTypes.BIND_OPTS opts) { }
        void IBindCtx.GetBindOptions(ref System.Runtime.InteropServices.ComTypes.BIND_OPTS opts) { }
        void IBindCtx.GetRunningObjectTable(out System.Runtime.InteropServices.ComTypes.IRunningObjectTable tab) { }
        void IBindCtx.RegisterObjectParam(string s, object obj) { }
        void IBindCtx.GetObjectParam(string s, out object obj) { }
        void IBindCtx.EnumObjectParam(out System.Runtime.InteropServices.ComTypes.IEnumString enumString) { }

        /* Problem here https://msdn.microsoft.com/en-us/library/windows/desktop/ms693771(v=vs.85).aspx
         * C++ Syntax is 
         * HRESULT RevokeObjectParam( [in] LPOLESTR pszKey );
         * LPOLESTR is a null terminated 2 byte based string so UnmanagedType.LPWStr ought to work
         * 
         */
        //void IBindCtx.RevokeObjectParam(string a) { }
        void IBindCtx.RevokeObjectParam([MarshalAs(UnmanagedType.LPWStr)] string a) { }

        /*
         * Compile errors are
         * Class1.cs(25,14,25,40): error CS0539: 'IBindCtx.RevokeObjectParam' in explicit interface declaration is not a member of interface
         * Class1.cs(6,18,6,24): error CS0535: 'ComInterfacesInCSharp.Class1' does not implement interface member 'System.Runtime.InteropServices.ComTypes.IBindCtx.RevokeObjectParam(string)'
         */
    }
}

順便說一句,如果您有一個Web資源詳細介紹了C#中的這些接口,那真是太棒了!

您提供的鏈接很棒! 它回答了我的問題,那是什么是正確的方法簽名。 現在,我絕對來自Microsoft。

盡管可以從Microsoft的參考源站點中找到許多源代碼定義,但這並不是發現程序集中定義的方法的簽名的唯一選擇。

學習使用Visual Studio的對象瀏覽器 查看菜單->對象資源管理器(或按F2鍵)。

在實現接口的特定情況下,您可以讓Visual Studio自動為您實現接口。 右鍵點擊接口名稱廣告,選擇“實施接口”。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM