我怎样才能在C#中使用这样的codegen类?

Ins*_*ter 1 .net c# code-generation code-duplication

我在项目中有多个类,除了类的名称之外完全相同.基本上,它们代表在运行时从配置文件加载的美化枚举.这些类看起来像这样:

public class ClassName : IEquatable<ClassName> {
    public ClassName(string description) {
        Description = description;
    }

    public override bool Equals(object obj) {
        return obj != null &&
            typeof(ClassName).IsAssignableFrom(obj.GetType()) && 
            Equals((ClassName)obj);
    }

    public bool Equals(ClassName other) {
        return other != null && 
            Description.Equals(other.Description);
    }

    public override int GetHashCode() {
        return Description.GetHashCode();
    }

    public override string ToString() {
        return Description;
    }

    public string Description { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

我认为没有理由复制此文件并多次更改类名.当然,有一种方法可以列出我想要的类,并自动为我创建它们.怎么样?

Cra*_*ntz 12

我建议使用T4.这个代码片段的一个重要优点是,如果您更改模板,那么所有代码​​都将更新以匹配.

把它放在带扩展名的文件中 .tt

<#@ template language="C#" #>
<#@ output extension=".codegen.cs" #>
<#@ assembly name="System.dll" #>
<#@ import namespace="System" #>
// <auto-generated>
// This code was generated by a tool. Any changes made manually will be lost
// the next time this code is regenerated.
// </auto-generated>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyStuff
{
<# foreach (string classname in classes) {#>
    public class <#= classname #> : IEquatable<ClassName> 
    {
            public <#= classname #>(string description) {
        Description = description;
    }

    public override bool Equals(object obj) {
        return obj != null &&
            typeof(<#= classname #>).IsAssignableFrom(obj.GetType()) && 
            Equals((<#= classname #>)obj);
    }

    public bool Equals(<#= classname #>other) {
        return other != null && 
            Description.Equals(other.Description);
    }

    public override int GetHashCode() {
        return Description.GetHashCode();
    }

    public override string ToString() {
        return Description;
    }

    public string Description { get; private set; }
    }
    }

<# } #> 
}

<#+ string[] classes = new string[] {  "Class1",
                                       "Class2" };
#>
Run Code Online (Sandbox Code Playgroud)

VS将为您生成源文件.只需classes在需要新类时添加到数组中.