我怎样才能在 Visual Studio 2015 中获得用户选择的代码

How could I get user selected code in Visual Studio 2015

selected.Contains 抛出空指针异常,即使用户在调用该方法之前选择了一些代码。

this.package = package;        

string selected;
selected = (string)this.ServiceProvider.GetService(typeof(TextSelection));

if (selected.Contains("for")) 
{
    MessageBox.Show("user "  + "selected" + selected);
}

我会一路送你。

 private IVsEditorAdaptersFactoryService GetEditorAdaptersFactoryService()
 {
        IComponentModel componentModel =(IComponentModel)GetService(typeof(SComponentModel));
        return componentModel.GetService<IVsEditorAdaptersFactoryService>();
 }   
private Microsoft.VisualStudio.Text.Editor.IWpfTextView GetTextView()
 {
        IVsTextManager textManager = (IVsTextManager)GetService(typeof(SVsTextManager));
        if (textManager == null)
            return null;
        IVsTextView textView = null;
        textManager.GetActiveView(1, null, out textView);
        if (textView == null)
            return null;
        return GetEditorAdaptersFactoryService().GetWpfTextView(textView);
 }
public void SomeFUnction()
{
    Microsoft.VisualStudio.Text.Editor.IWpfTextView textView = GetTextView();
    if (textView != null)
    {
                    SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition;
    }
}

现在您已将插入符号定位在您身上,以找出那里的内容。 像 textView.GetTextElementSpan(caretPosition).GetText()

这样的东西