.NET中使用T4消除代码重复2013-11-11 cnblogs 幸福框架背景我需要为int、long、float等这些数值类型写一些扩展方法,但是我发现他们不是一个继承体 系,我的第一个思维就是需要为每个类型重复写一遍扩展方法,这让我觉得非常不爽,但是我还是不情愿的写 了,等int和long写完后,我突然觉得我可以让T4帮我写,而且C#支持部分类,就更爽了。用T4实现模 板(写代码的代码)
<#@ template debug="false" hostspecific="false" language="C#" #><#@ assembly name="System.Core" #><#@ import namespace="System.Linq" #><#@ import namespace="System.Text" #><#@ import namespace="System.Collections.Generic" #><#@ output extension=".cs" #>using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.IO;namespace Happy.Infrastructure.ExtentionMethods{public static partial class Check{<#foreach(var type in new string[]{ "double", "int" }){#>/// <summary>/// 名称为<paramref name="variableName"/>的参数或变量的值(<paramref name="value"/>)必须在某个范围。/// </summary>public static void MustBetween(this <#= type #> value, string variableName, <#= type #> start, <#= type #> end){Require(value >= start && value <= end, String.Format(Messages.Error_MustBetween, variableName, start, end));}/// <summary>/// 名称为<paramref name="variableName"/>的参数或变量的值(<paramref name="value"/>)必须大于指定的值。/// </summary>public static void MustGreaterThan(this <#= type #> value, string variableName, <#= type #> target){Require(value > target, String.Format(Messages.Error_MustGreaterThan, variableName, target));}/// <summary>/// 名称为<paramref name="variableName"/>的参数或变量的值(<paramref name="value"/>)必须大于等于指定的值。/// </summary>public static void MustGreaterThanEqual(this <#= type #> value, string variableName, <#= type #> target){Require(value > target, String.Format(Messages.Error_MustGreaterThanEqual, variableName, target));}<#}#>}}
我对了吗?