65.9K
CodeProject 正在变化。 阅读更多。
Home

使用宏自动化代码编写过程

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.63/5 (31投票s)

2005年3月13日

CPOL

11分钟阅读

viewsIcon

181473

downloadIcon

2562

本文介绍了用于加快和简化Visual Studio 2003代码编写过程的文档宏。

变更

请参阅历史记录以获取完整的变更日志。zip文件中包含的文档除了宏的变更日志外,还包含更新的文档。

引言

在为源文件编写代码和文档时,需要完成许多手动工作。通常,您会遵循特定的代码标准,并且会频繁编写一些只需稍作修改的代码。我开发了一套宏来简化我的日常工作,从而提高我的开发效率。这些宏采用了我们公司的代码标准,希望与您的标准差别不大,并且可以进行微调以匹配您的标准。

这些宏侧重于内联XML文档、region块、自动化和重构。它们适用于Visual Studio 2003,主要支持C#,但有些宏也支持VB.NET。

安装

下载提供的文件并按照下面的说明操作

对于 VS 2005

  1. 打开宏资源管理器 (Alt+F8 或 View -> Other windows -> Macro Explorer)
  2. 在宏资源管理器中右键单击“Macros”,然后选择“Load Macro Project”
  3. 选择“Meridium.vsmacros”并单击“Add”
  4. 运行宏 Meridium.Documentator.FixKeyMapping 来安装快捷键
  5. [可选] 如果您已安装Resharper插件,请运行 Meridium.Documentator.FixKeyMappingsAfterResharperInstallation
  6. 准备就绪

对于 VS 2003

  1. 如果您使用的是默认设置,请创建一个新的键盘映射方案 (Tools -> Options -> Environment -> Keyboard -> Save as)
  2. 在Visual Studio中加载宏项目“Meridium.vsmacros” (Tools -> Macros -> Load Macro project...)
  3. 打开宏资源管理器 (Alt+F8 或 Tools -> Macros -> Macro Explorer)
  4. 运行宏 Meridium.Documentator.FixKeyMapping 来安装快捷键
  5. 准备就绪

使用宏

宏的完整解释在手册中,但我将简要介绍主要功能。

例如,如果您写了一个方法,看起来像这样

public int MyMethod(string name, int maxNo, Font font) 
{
    //my code
}

然后调用“Document and regionize”宏 (Ctrl+d),您将得到如下结果

#region public int MyMethod(string name, int maxNo, Font font)
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="maxNo"></param>
/// <param name="font"></param>
/// <returns></returns>
public int MyMethod(string name, int maxNo, Font font) 
{
    //my code
}
#endregion

光标会放在第一个XML文档标签(<summary>)处,您可以开始编写文档。如果您还启用了EnableTabMapping,则可以使用Tab和Shift+Tab在XML文档部分的各个标签之间移动。

它还支持更新,因此如果您添加参数或更改参数顺序,然后再次调用宏,文档和区域将得到更新。

另一个主要的宏是PasteTemplate宏,它通过模板支持自动化和重构。目前,模板是硬编码在宏中的,但您可以轻松修改它们以满足您的需求。

例如,如果您想创建一个 try catch 子句,请输入以下文本

tryc

并调用PasteTemplate宏 (Ctrl+J),您将得到如下结果

try 
{
} 
catch(Exception ex) 
{
}

还存在更多自动化功能。尝试使用 foritrycmtrycftryf gpspgsp

创建事件时支持更复杂的自动化。如果您定义了以下事件

public event EventHandler MyEvent;

并调用PasteTemplate宏,您将得到以下代码

#region public event EventHandler MyEvent
/// <summary>
/// This event is fired when
/// </summary>
public event EventHandler MyEvent;
#endregion
#region protected virtual void OnMyEvent(EventArgs e)
/// <summary>
/// Notifies the listeners of the MyEvent event
/// </summary>
/// <param name="e">The argument to send to the
    listeners</param>
protected virtual void OnMyEvent(EventArgs e) 
{
    if(MyEvent != null) 
    {
        MyEvent(this,e);
    }
}
#endregion

这节省了大量时间。

同一个宏也增加了重构功能。例如,如果您想将一个字段转换为属性,

public string Name;

将光标放在行末并调用PasteTemplate宏,您将得到如下结果

public string Name;
    get { return _name; }
    set { _name = value; }
}
private string _name;

然后将“Document and regionize”宏添加到该功能中,只需几秒钟,您就可以重构和记录您的字段了。

字段重构方法包含几种根据字段初始化情况变化的变体,有关完整描述请参阅手册。我添加了一些其他重构类型,但您需要查阅手册以获取完整规范。

下面简要描述了一些宏,完整描述存在于(是的,您猜对了)手册中。

快捷方式 摘要

文档化并区域化此代码

Ctrl + d 为当前代码元素添加XML文档的更新,并在该区域周围加上#region #endregion指令。

粘贴模板

Ctrl + Shift+ j 检查关键字并粘贴适当的模板。可与Borland的模板函数和VS 2005的代码片段进行比较。

切换父区域

Ctrl + m, Ctrl + m 切换父#endregion块。

展开所有区域

Ctrl + Shift + + 展开所有#endregion块。

折叠所有区域

Ctrl + Shift + - 折叠所有#endregion块。

创建文档标题

Ctrl + Shift + Alt + h 创建文档标题。

格式化当前文档

Ctrl + Shift + d 格式化当前文档,可与Edit.FormatSection进行比较。

升序排序行

Ctrl + Alt + s 将选定行按升序排序。
降序排序行 Ctrl + Alt + Shift + s 将选定行按降序排序。

安装文档工具栏项

安装用户配置的工具栏和工具箱中的项。

根据标签操作

Ctrl + < 如果光标位于XML文档块内,则前进到下一个XML文档标签。

根据Shift Tab操作

Ctrl + > 如果光标位于XML文档块内,则转到上一个XML文档标签。

修复按键映射

将所有快捷键连接到宏,但“Act on tab”和“Act on shift tab”宏除外。
移除按键映射 移除宏的所有按键映射。(但不恢复任何被覆盖的宏)
Resharper安装后修复按键映射 修复Resharper、DocumentatorMacros和VisualStudio之间的一些按键映射冲突。
MakeCData 将选定的文本包装在<![CDATA[ ... ]]>结构中。
FixHTMLValidationErrors 修复HTML文档中常见的验证错误。
KillLine Ctrl + Shift + k 删除该行剩余的部分
EnterCodeComment Ctrl + Shift + c 创建一个格式为<date>: <domain>\<user>的注释
EnterCodeRemark Ctrl + Shift + Alt + c 将备注添加到当前类的文档中
RemoveWordPasteHtmlTags 从Word粘贴格式化文本时,移除Word特有的HTML标签和属性。
HTMLEncode 对标记的文本进行HTML编码

自动文档化

对于属性、索引器和一些方法,当调用Document(AndRegionize)宏时,将提供默认文档。

以下元素将被自动文档化

方法/元素 示例
构造函数

<summary>
初始化 <b>MyType</b> 类的新实例。
</summary>

析构函数
(Finalize)

<summary>
在垃圾回收器回收<b>MyType</b>之前,释放非托管资源并执行其他清理操作。
the <b>MyType</b> is reclaimed by garbage collection.
</summary>

void Dispose(...)

<summary>
释放 <b>MyType</b> 使用的资源
</summary>

string ToString(...) <summary>
返回一个<see cref="String"/>,表示当前的<see cref="MyType">
</summary>
<returns>A <see cref="String"/> that represents the current <see cref="MyType">.</returns>
bool Equals(MyType o) <summary>
确定指定的<see cref="MyType"> 是否等于当前的
the <b>MyType</b>.
</summary>
<param name="o">与当前<see cref="MyType">进行比较的<see cref="MyType">。</param>
<returns>If the specified <see cref="MyType"> is equal to the current <b>MyType</b>, returns true; otherwise, returns false.</returns>
otherwise, false.</returns>
bool Equals(MyType a, MyType b) <summary>
确定指定的<see cref="MyType"> 实例是否被视为相等。
</summary>
<param name="a">要与<see cref="MyType">比较的第一个<see cref="MyType"></param>
<param name="b">要与<see cref="MyType">比较的第二个<see cref="MyType"></param>
<returns> If <i>a</i> is the same instance as <i>a</i> or if both are null references or if <c>a.Equals(b)</c> returns true; otherwise, returns false. </returns>
or if both are null references or if <c>a.Equals(b)</c> returns true; otherwise, false. </returns>
int GetHashCode(...) <summary>
用作特定类型的哈希函数,适用于哈希算法和哈希表等数据结构。
</summary>
<returns>当前<see cref="MyType">的哈希代码。</returns>
属性

<summary>
[Get/Set]s the [PropertyName] of the [ClassType]
</summary>

索引器 (Indexers)

<summary>
[Get/Set]s <see cref="[IndexerType]"/> item identified by the given arguments of the [ClassType]
</summary>

void ControlName_EventName(object param1, [Any]Args param2)

<summary>
[ControlName][eventName] 事件被触发时调用此方法。
</summary>
<param name="param1">触发事件的<see cref="object"> </param><param name="param2">事件的<see cref="AnyArgs"></param>

Clone(Object obj)

<summary>
创建当前实例的副本。
</summary>
<param name="source"></param>
<returns>新对象,它是此实例的副本。</returns>
bool Contains(Object obj) <summary>
返回一个值,指示指定的<see cref="Object">是否包含在<see cref="Class1">中。
</summary>
<param name="a"><see cref="Class1">中查找的<see cref="Object"></param>
<see cref="Class1"/></param>
<returns><b>true</b> if the <i>Object</i> parameter is a member
of the <see cref="Class1">; otherwise, <b>false</b>.</returns>
bool IsWord(..) <returns>True if it is word, otherwise false.</returns>
bool IsWord1Word2WordN(...) <returns>True if word1 word2 is wordn, otherwise false.</returns>
[Any]Format(string format, param object[] args) <param name="format">A string containing zero or more format specifications.</param>
<param name="args">An array of objects to format.</param>
int Compare(MyType x, MyType y) <summary>Compares two objects and returns a value indicating whether one is less than,
equal to, or greater than the other.<summary>
<param name="x">The first object to compare.</param><param name="y">The second object to compare.</param>
<returns>A 32-bit signed integer that indicates the relative order
of the objects being compared. The return value has these meanings
含义
Less than zero x less than y.
Zero x is equal to y.
Greater than zero x is greater than y.
</returns>
int CompareTo(MyType o) <summary>Compares the current instance with another object of the same type.</summary>
<param name="o">The <see cref="MyType"> to compare with this instance.</param>
<returns>A 32-bit signed integer that indicates the relative order
of the objects being compared. The return value has these meanings
含义
Less than zero This instance is less than 0.
Zero This instance is equal to 0.
Greater than zero This instance is greater than 0.
</returns>

关注点

I have to thank Roland Weigelt for his inspiring GhostDoc and some other macros (region expand). The Key mapping binder is also found on the net, I can't remember where though.

The upcoming Visual Studio 2005 will be a good update for the automation and refactoring with the introduction of code snippets.

历史

2007-06-28 - 2.5.1.0

Contains support for

  • New macros

    • FixKeyMappingsAfterReSharper25Installation - renamed from FixKeyMappingsAfterReSharperInstallation. Used to setup keymappings after Resharper 2.5 has been installed
    • FixKeyMappingsAfterResharper3Installation - Used to setup keymappings after Resharper 3 has been installed
    • KillHtmlStyleAndClassFormatting - removes style and class formatting from selected HTML code

  • Enhancements /Bugfixes

    • PasteTemplate - added the disp keyword
    • EnterCodeRemark - Better output of code remarks
    • RemoveWordPasteHtmlTags - removes all mso-* styles, lang attributes from span tags.
    • DocumentThis - Auto documents public void Dispose(bool disposing)

007-01-25 - 1.4.0.0

Version 1.4.0.0 is a branch from v 1.3.0.0 that supports Visual Studio 2003. The 2003 branch misses all additional functionality after version 1.3.0.0 and has to be developed separately. I have no intention (personal need) to bring the 2003 branch up to the same functionality as the 2005 branch but if you feel like implementing in the 2003 branch, please send me your modifications and I can update this project.

  • New macros

    • FixKeyMappingsAfterResharper203Installation - updates the keyboard shortcuts

2007-01-15 - 2.5.0.0

  • Supports Visual Studio 2005 and

  • New macros

    • KillLine - Kills the rest of the line
    • EnterCodeComment - Enters a code comment on the format <date>: <domain>\<user>
    • EnterCodeRemark - Appends a remark comment to the current class documentation
    • RemoveWordPasteHtmlTags - Removes Word specific HTML tags and attributes if you paste some formatted text from Word.
    • HTMLEncode - HTML encodes the marked text

  • Enhancements/Bugfixes

    • FixKeyMappingsAfterResharperInstallation - Supports Resharper 2.5
    • CollapseAllRegions - now supports nested regions (thanks to DragonWang_SFIS) and commented ones.
    • PasteTemplate
      • Indentions now work better.
      • PropertyChanged events now fully documented
      • Field to property now recognizes private _variables and converts them to public Properties
      • for to foreach matches better
    • MakeCData - now does not HTML encode the selected text before creating the CData section.
    • FixHTMLValidationErrors
      • Combines multiple style attributes
      • Removes language and ms_positioning attributes from div tags
      • Removes topmargin attributes from body tags
      • Adds alt attributes to images if missing (defaults to the same as src)
    • DocumentThis
      • Better support for generics
      • Now supports explicit generic interfaces
      • Autodocuments [Any]Format(string format, param object[] args) methods
      • Autodocuments Compare methods
      • Regionizes better on long declarations
  • Updated installation instructions

2006-02-27 - 2.0.0.0

  • Supports Visual Studio 2005. For VS2003 support please use version 1.3.0.0.

  • New macros

    • MakeCData
    • Fix HtmlValidationErrors

  • Enhancements/Bugfixes

    • FixKeyMappingsAfterResharperInstallation - Supports
    • DocumentAndRegionizeThis - now works with VB.NET
  • CommentSection - Macro removed (VS 2005 internal CommentSection now works with XML/HTML/Javascript code
  • Plus an additional lot of enhancements and bugfixes

2005-10-27 - 1.3.0.0

  • Even more functions and enhancements

  • New macros

    • LoadColorableSettings
    • SaveColorableSettings
    • FixKeyMappingsAfterReSharperInstallation

  • Enhancements/Bugfixes

    • PasteSeeParameterXmlDocTag
      • Now works with delegates, Structs, Interfaces, Namespaces
    • DocumentAndRegionize
      • Added autodocumentation features on
        • get/set properties
        • indexers (interface)
        • "Is" methods

2005-06-08 - 1.2.0.0

  • Some more functions and enhancements.
  • Now more compatible with ReSharper

  • New Macros

    • PasteSeeParameterXmlDocTag
    • DocumentThis
    • RemoveKeyMappings

  • Enhancements/Bugfixes

    • DocumentAndRegionize
      • Added autodocumentation features on
        • 属性
        • 索引器 (Indexers)
        • Event methods
        • Clone methods
        • Contains methods
    • PasteTemplate
      • Changed shortcut to Ctrl + Shift + j (to work with ReSharper)
      • fori template changed
      • Added templates forj, fork, test
    • ActOnTab
      • Changed shortcut to Ctrl + < (didn't want to lock up the tab key any longer)
    • ActOnShiftTab
      • Changed shortcut to Ctrl + > (didn't want to lock up the tab key any longer)
  • EnableTabMappings - Removed
  • DisableTabMappings - Removed

2005-04-07 - 1.1.0.0

  • This release contains a few more functions and bugfixes

  • Enhancements/Bugfixes

    • PasteTemplate
      • Added Singleton Template in PasteTemplate
      • Convert to property now recognizes static properties
    • DocumentAndRegionize
      • Document and Regionize now actually fills in documentation for a few methods
      • Empty documentation tags are now removed
      • Now Documents classes (not regionizes them)
      • Regionizes variables in structs
      • Better general quality of output XML documentation
      • Don't add <return> tags on properties anymore
      • Adds <value> tags on properties
      • Basic XML documentation now functions correctly when using this macro several times
      • No longer divides single tags into start/end tags when not appropriate

2005-03-15 - 1.0.0.1

  • Removed the reference to Se.MeridiumKalmar (thanks enigmacs).

2005-03-13 - 1.0.0.0

  • 首次公开发布
© . All rights reserved.