CSDN博客

img beyond_ml

在VS.NET2003中使用Macro生成自定义异常代码

发表于2004/6/24 23:07:00  780人阅读

 

写程序的时候,每次到了要自定一个异常,总是要啰里啰唆的敲上一大堆代码,而且这些代码细想起来也就无非是声明一个从System.Exception继承的类,然后在类中添加三个构造函数和一个自定错误的消息字符串,为了简化这种体力劳动,我利用VS2003自带的宏编辑器写了一小段代码,来帮助我自动完成这些东西。

1.首先打开你的宏编辑器(在VS2003种按下ALT+F11): 把下面的代码copy带编辑器中.

Imports EnvDTE
Imports System.Diagnostics
Imports Microsoft.Office.Core

    Sub AddException()
        Dim input As String
        Dim expName As String
        Dim expMsg As String

        Dim split As String() = Nothing
        Dim delimStr As String = ",.:;"
        Dim delimiter As Char() = delimStr.ToCharArray()
        Dim objTextDoc As TextDocument
        Dim objEditPt_Begin As EditPoint
        Dim objEditPt_End As EditPoint

        input = InputBox("Input as : ExceptionName;Message", "Auto Complete Exception", String.Empty)

        If input.Length = 0 Then
            Return
        End If

        split = input.Split(delimiter)

        expName = split(0)

        If split.Length = 2 Then
            expMsg = split(1)
        Else
            expMsg = "General Exception of " & expName
        End If


        DTE.UndoContext.Open("AddException", False)

        objTextDoc = DTE.ActiveDocument.Object("TextDocument")
        objEditPt_Begin = objTextDoc.Selection.ActivePoint.CreateEditPoint()

        objEditPt_Begin.Insert("public class " & expName & ": System.Exception " & vbCrLf)
        objEditPt_Begin.Insert("{" & vbCrLf)
        objEditPt_Begin.Insert("const string errMsg = """ & expMsg & """;" & vbCrLf)
        objEditPt_Begin.Insert(vbCrLf)
        objEditPt_Begin.Insert("public " & expName & "():base( errMsg )" & vbCrLf)
        objEditPt_Begin.Insert("{}" & vbCrLf)
        objEditPt_Begin.Insert(vbCrLf)
        objEditPt_Begin.Insert("public " & expName & "(string auxMessage):base( String.Format( ""{0} - {1}"",errMsg, auxMessage ))" & vbCrLf)
        objEditPt_Begin.Insert("{}" & vbCrLf)
        objEditPt_Begin.Insert(vbCrLf)
        objEditPt_Begin.Insert("public " & expName & "(string auxMessage, Exception inner ):base( String.Format( ""{0} - {1}"",errMsg, auxMessage ), inner)" & vbCrLf)
        objEditPt_Begin.Insert("{}" & vbCrLf)
        objEditPt_Begin.Insert("}" & vbCrLf)

        objEditPt_End = objTextDoc.Selection.ActivePoint.CreateEditPoint()
        objEditPt_Begin.LineUp(13)

        objEditPt_Begin.SmartFormat(objEditPt_End)

        DTE.UndoContext.Close()

    End Sub

2.在MacroExplorer中用右键菜单使这个宏运行起来。

3.宏运行后,然后会出现一个输入框,按照如下格式输入:ExceptionName splitter ExceptionMsg

例如:MyException;This is my exception

回车后就会在文件中生成你想要的Exception代码了,瞧一瞧,感觉还挺Cool 吧?你还可以在Option->keyboard中给这个Macro分配一个快捷键,例如:ALT+1,再试试,感觉写代码的痛苦程度至少减轻了10%。:)

    

0 0

相关博文

我的热门文章

img
取 消
img