我正在尝试使用插件向类添加一些属性。我可以使用以下代码来工作,除了我希望每个包含在[]中的新行上的属性。我该怎么做?
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
]。
答案 0 :(得分:0)
您正在使用的方法的签名:
CodeAttribute AddAttribute(
string Name,
string Value,
Object Position
)
String.Empty
字段作为第二个参数Position
。在代码中,为0
设置此参数三次,VS认为这是相同的属性。所以使用一些索引,如: func.AddAttribute("Name", "\"" + func.Name + "\"", 1);
func.AddAttribute("Active", "\"" + "Yes" + "\"", 2);
func.AddAttribute("Priority", "1", 3);
如果您不想使用索引,请使用-1
值 - 这将在收集结束时添加新属性。
答案 1 :(得分:0)
基础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");
}
}
}