使用filecodemodel添加属性

问题描述:

我想向使用插件的类添加一些属性。我可以得到下面的代码来工作,除了我希望新行上的属性都包含在[]中。我该怎么做呢?使用filecodemodel添加属性

if (element2.Kind == vsCMElement.vsCMElementFunction) 
{ 
    CodeFunction2 func = (CodeFunction2)element2; 
    if (func.Access == vsCMAccess.vsCMAccessPublic) 
    { 
     func.AddAttribute("Name", "\"" + func.Name + "\"", 0); 
     func.AddAttribute("Active", "\"" + "Yes" + "\"", 0); 
     func.AddAttribute("Priority", "1", 0); 
    } 
} 

属性被添加到公共方法类似

[Name("TestMet"), Active("Yes"), Priority(1)] 

凡为我想把它当作

[Name("TestMet")] 
[Active("Yes")] 
[Priority(1)] 
public void TestMet() 
{} 

而且我怎么能添加一个属性没有任何值,如[PriMethod] 。

签名为您所使用的方法:

CodeAttribute AddAttribute(
    string Name, 
    string Value, 
    Object Position 
) 
  1. 如果您不需要的属性值,使用String.Empty场第二个参数
  2. 第三个参数是为Position。在你的代码中,你为0设置了这个参数三次,VS认为这是相同的属性。因此,使用一些指标,这样的:

func.AddAttribute("Name", "\"" + func.Name + "\"", 1);
func.AddAttribute("Active", "\"" + "Yes" + "\"", 2);
func.AddAttribute("Priority", "1", 3);

如果你不想使用索引,使用-1值 - 这将在集合的末尾增加新的属性。

More on MSDN

+0

感谢您的输入反应。我曾尝试使用0,1和2作为相对位置,但位置与上述相同。 – user393148

+0

我也试过string.empty。 Thta给了我PriMethod()而不仅仅是PriMethod。 – user393148

+0

@ user393148尝试使用'-1'。另外我忘了提及,该索引从“1”开始,因此请尝试使用1,2,3. – VMAtm

基础AddAttribute方法不支持这一点,所以我写了一个扩展方法为我做到这一点:

public static class Extensions 
{ 
    public static void AddUniqueAttributeOnNewLine(this CodeFunction2 func, string name, string value) 
    { 
     bool found = false; 
     // Loop through the existing elements and if the attribute they sent us already exists, then we will not re-add it. 
     foreach (CodeAttribute2 attr in func.Attributes) 
     { 
      if (attr.Name == name) 
      { 
       found = true; 
      } 
     } 
     if (!found) 
     { 
      // Get the starting location for the method, so we know where to insert the attributes 
      var pt = func.GetStartPoint(); 
      EditPoint p = (func.DTE.ActiveDocument.Object("") as TextDocument).CreateEditPoint(pt); 

      // Insert the attribute at the top of the function 
      p.Insert(string.Format("[{0}({1})]\r\n", name, value)); 

      // Reformat the document, so the new attribute is properly aligned with the function, otherwise it will be at the beginning of the line. 
      func.DTE.ExecuteCommand("Edit.FormatDocument"); 
     } 

    } 
}