简体   繁体   English

用于创建类和接口的Visual Studio模板或代码段

[英]Visual studio Templates or Code snippets to create classes and interfaces

I am writing some Unit Tests and would like to create a Template/Code Snippet (Not sure what the exact terminology is in Visual studio). 我正在编写一些单元测试,并想创建一个模板/代码片段(不确定Visual Studio中的确切术语)。 In simple terms i would like to create some boiler plate code which I can re-use. 简单来说,我想创建一些可以重复使用的样板代码。

ie, User will enter a Name of the class and use it to create a Interface, classes and some method definitions. 即,用户将输入类的名称,并使用它来创建接口,类和一些方法定义。

eg, If a user enters VATRate 例如,如果用户输入VATRate

IVATRate will be created in xyz.Common.Interfaces IVATRate将在xyz.Common.Interfaces中创建

VATRateRepository will be created in xyz.BusinessLayer VATRateRepository将在xyz.BusinessLayer中创建

VATRateRepositoryTests will be created in xyz.BusinessLayer.Tests VATRateRepositoryTests将在xyz.BusinessLayer.Tests中创建

Methods in VATRateREpositoryTests will be defined InsertVATRate_ShouldInsertNewRecord_WhenVatRateDoesNotExist UpsertVATRate_ShouldUpdateRecord_WhenRecordExist GetAllVATRate_ReadsAllRecords 将定义VATRateREpositoryTests中的方法InsertVATRate_ShouldInsertNewRecord_WhenVatRateDoesNotExist UpsertVATRate_ShouldUpdateRecord_WhenRecordExist GetAllVATRate_ReadsAllRecords

etc.. 等等..

You can automate it with my Visual Commander extension. 您可以使用我的Visual Commander扩展程序对其进行自动化。 The code for a command in C# will look like this: C#中命令的代码如下所示:

References: Microsoft.VisualBasic 参考:Microsoft.VisualBasic

using EnvDTE;
using EnvDTE80;
using Microsoft.VisualBasic;

public class C : VisualCommanderExt.ICommand
{
    public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package) 
    {
        string className = Microsoft.VisualBasic.Interaction.InputBox("Class name", "Create tests",
                    "VATRate", -1, -1);
        EnvDTE.ProjectItem f = DTE.ItemOperations.AddNewItem("Visual C# Items\\Code\\Class", className + "RepositoryTests.cs");
        EnvDTE.CodeClass c = FirstClass(FirstNamespace(f.FileCodeModel.CodeElements).Children);
        c.AddFunction("Insert" + className, vsCMFunction.vsCMFunctionFunction, vsCMTypeRef.vsCMTypeRefVoid);
    }

    private EnvDTE.CodeNamespace FirstNamespace(EnvDTE.CodeElements elements)
    {
        foreach(EnvDTE.CodeElement c in elements)
        {
            if(c is EnvDTE.CodeNamespace)
            return c as EnvDTE.CodeNamespace;
        }
        return null;
    }

    private EnvDTE.CodeClass FirstClass(EnvDTE.CodeElements elements)
    {
        foreach (EnvDTE.CodeElement c in elements)
        {
            if (c is EnvDTE.CodeClass)
                return c as EnvDTE.CodeClass;
        }
        return null;
    }
}

If you select a project in your solution and run the command from the VCmd menu, it will create the following file: 如果您在解决方案中选择一个项目并从VCmd菜单运行命令,它将创建以下文件:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM