【问题标题】:add attribute using filecodemodel使用 filecodemodel 添加属性
【发布时间】:2011-08-19 18:53:41
【问题描述】:

我正在尝试使用插件向类添加一些属性。我可以使以下代码正常工作,除了我希望每个包含在 [] 中的新行上的属性。我该怎么做?

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]。

【问题讨论】:

    标签: c# .net visual-studio attributes


    【解决方案1】:

    您正在使用的方法的签名:

    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,1 和 2 作为相对位置,但位置与上面相同。
    • 我也试过 string.empty。 Thta 给了我 PriMethod() 而不仅仅是 PriMethod。
    • @user393148 尝试使用-1。另外我忘了提,这里的索引是从1开始的,所以尽量用1、2、3。
    • 不走运。我刚刚尝试了 (0, -1, -1 ) (1, -1, -1), (1,2,3),但结果是一样的。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      • 2021-05-24
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多