开发者

add attribute using filecodemodel

开发者 https://www.devze.com 2023-03-29 15:04 出处:网络
I am trying to add few attributes to a class using an addin. I can get the following code to working, except that I want the attributes on new lines each contained within []. How do I do this?

I am trying to add few attributes to a class using an addin. I can get the following code to working, except that I want the attributes on new lines each contained within []. How do I do this?

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);
    }
}

Attributes are added to the public method like

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

Where as I want it as

[Name("TestMet")]
[Active("Yes")]
[Priority(1)]开发者_运维知识库
public void TestMet()
{}

Also how can I add an attribute without any value, like [PriMethod].


Signature for the method you are using:

CodeAttribute AddAttribute(
    string Name,
    string Value,
    Object Position
)
  1. If you don't need value for the attribute, use String.Empty field for the second parameter
  2. Third parameter is for the Position. In your code you set this parameter three times for the 0, and VS thinks that this is the same attribute. So use some index, like that:

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

If you don't want to use index, use -1 value - this will add new attribute at the end of collection.

More on MSDN


The base AddAttribute method does not support this, so I wrote an extension method to do this for me:

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");
        }

    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消