【问题标题】:vs2010 automation : Get the text value of a EnvDTE.CodeElementvs2010 自动化:获取 EnvDTE.CodeElement 的文本值
【发布时间】:2011-05-02 11:37:59
【问题描述】:

所以我在玩EnvDTEEnvDTE.CodeModel API,我想知道是否有办法获取CodeElement 表示的文本值。

假设我有一个CodeAttribute,有没有办法获得string 代表CodeAttribute 所代表的内容,即[MyAttribute(value="myvalue")]

我知道可以使用CodeElement 的各种属性来重构代码,至少在某些情况下是这样,但对于某些情况,似乎只获取文本会更容易。

谢谢!

【问题讨论】:

    标签: c# .net visual-studio visual-studio-2010 code-generation


    【解决方案1】:

    CodeElement 接口具有属性StartPointEndPoint,它们表示缓冲区中元素的开始和结束。这些包含可以传递给IVsTextLines.GetLineText 等方法的行号/列,并返回您正在寻找的值。

    要获取给定CodeElementIVsTextLines,您可以执行以下操作

    CodeElement ce = ...;
    TextDocument td = ce.StartPoint.Parent;
    IVsTextLines lines = td as IVsTextLines;
    

    【讨论】:

    • 我想我的下一个问题应该是,如何获得对IVsTextLines 的引用?我还想知道这是否需要在编辑器中打开文件,从而在文本缓冲区中打开。我正在尝试使用Project.CodeModel 在项目/解决方案范围内实现一些东西,所以我将在不打开文件的情况下探索模型。不过这可能是不可能的。
    • @MasterMorality 你最终弄清楚如何获得对 IVsTextLines 的引用了吗?
    【解决方案2】:
      void WriteMapping(CodeProperty codeProperty)
     {
       WriteLine("");
       WriteLine("///CodeProperty");
       WriteLine("///<summary>");
       WriteLine("///"+codeProperty.FullName);
       WriteLine("///</summary>");
       if(codeProperty.Getter==null && codeProperty.Setter==null)
           return;
       if(codeProperty.Attributes!=null){
           foreach(CodeAttribute a in codeProperty.Attributes)
            {
                Write("["+a.FullName);
                if(a.Children!=null && a.Children.Count>0)
                {
                    var start=a.Children.Cast<CodeElement>().First().GetStartPoint();
                    var finish= a.GetEndPoint();
                    string allArguments=start.CreateEditPoint().GetText(finish);
    
                    Write("("+allArguments);
                }
        WriteLine("]");
            }
            }
       Write("public "+GetFullName(codeProperty.Type) +" "+codeProperty.Prototype);
    
        Write(" {");
        //if(codeProperty.Getter!=null && codeProperty.Getter.Access!=vsCMAccess.vsCMAccessPrivate)
            Write("get;");
        //if(codeProperty.Setter!=null)
            Write("set;");
        WriteLine("}");
    
       }
    

    【讨论】:

      【解决方案3】:

      除了@JaredPar 的回答之外,另一种方法是:

      public string GetText(CodeAttribute attribute)
      {
          return attribute.StartPoint.CreateEditPoint().GetText(attribute.EndPoint);
      } 
      

      就是这样!! (感谢@JaredPar 的指点)

      来源: http://msdn.microsoft.com/en-us/library/envdte.editpoint.gettext.aspx

      【讨论】:

        猜你喜欢
        • 2013-02-20
        • 2015-12-15
        • 2019-12-17
        • 2015-12-05
        • 1970-01-01
        • 2019-04-16
        • 2019-01-18
        • 1970-01-01
        • 2015-03-29
        相关资源
        最近更新 更多