除了一个类的名称外,我在一个项目中有多个完全相同的类。基本上,它们表示在运行时从配置文件加载的美化枚举。这些类如下所示:

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; }
}


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

最佳答案

我建议使用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" };
#>


VS将为您生成一个源文件。需要新类时,只需将其添加到数组classes中即可。

07-24 18:09
查看更多