了解 Component.GetService()

发布于 2024-10-12 05:03:18 字数 869 浏览 6 评论 0原文

我在用户控件中有一个带有此代码的方法

        public bool GetActiveDocument(ref EnvDTE.Document doc)
    {
        try
        {
            var dte = (DTE2)GetService(typeof(SDTE));
            doc = dte.ActiveDocument;
            if (doc == null)
            {
                MessageBox.Show("There isn't any file open in the Code Editor");
                return false;
            }
            else return true;
        }
        catch (Exception)
        {
            MessageBox.Show("There was a problem getting the actual file, verify if it is open");
            return false;
        }
    }

,我想将此方法移动到“代理”类,该类将充当 Visual Studio 和我的应用程序之间的中介。问题是 GetService 仅在控件内部调用时才能正确返回活动文档。当我将该方法移至 Proxy 类时,GetService 没有定义。我搜索到这个方法来自ComponentModel.Component,所以我让Proxy类从Component派生。一切都编译正常,但当我请求活动文档时总是会发生异常。我认为我不太了解 GetService() 方法的工作原理。请帮忙解决这个问题。

i have a method in a Usercontrol with this code

        public bool GetActiveDocument(ref EnvDTE.Document doc)
    {
        try
        {
            var dte = (DTE2)GetService(typeof(SDTE));
            doc = dte.ActiveDocument;
            if (doc == null)
            {
                MessageBox.Show("There isn't any file open in the Code Editor");
                return false;
            }
            else return true;
        }
        catch (Exception)
        {
            MessageBox.Show("There was a problem getting the actual file, verify if it is open");
            return false;
        }
    }

I want to move this method to a "Proxy" class that is going to act as an intermediary between Visual Studio and my application. The problem is that GetService only return the active document correctly if it is call inside the control. When i move that method to the Proxy class, GetService doesn't have definition. I search that this method comes from ComponentModel.Component, so i made the Proxy class derive from Component. Everything compiles OK but always when i ask for the active document an exception occurs. I thing that i'm not understanding well how works the GetService() method. Please help with this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初见你 2024-10-19 05:03:18

Component.GetService 在分配给组件的 Site 属性(假设有一个)的 ISite 实例上调用 IServiceProvider.GetService。您不需要让代理实例继承自 Component,但您需要授予它对 ISite/IServiceProvider 的访问权限。

Component.GetService invokes IServiceProvider.GetService on the ISite instance assigned to the component's Site property (assuming there is one). You shouldn't need to make your proxy instance inherit from Component, but you will need to give it access to the ISite/IServiceProvider.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文