在c#中,我想为DateTime结构编写扩展方法,以便按年、月等计算日期差异。
为了准备更改日期差异的计算,我为此制作了一个接口,并将其传递给静态扩展类中的一个配置方法。
具体来说:
public static class DateTimeExtension
{
private static IDateTimeDifference _dateDifference;
public static void Configure(IDateTimeDifference dateDifference )
{
DateTimeExtension._dateDifference = dateDifference;
}
public static int DiffFromInYears(this DateTime dateFromIncl, DateTime dateToExcl)
{
return _dateDifference.InYears(dateFromIncl, dateToExcl);
}
public static int DiffToInYears(this DateTime dateToExcl, DateTime dateFromIncl)
{
return _dateDifference.InYears(dateFromIncl, dateToExcl);
}
}我的服务配置如下所示:
var host = Host
.CreateDefaultBuilder()
.ConfigureServices(
(context, services) =>
{
services.AddSingleton<IDateTimeDifference>( s => new DateDifferenceFullPeriods() );
}
)
.Build();
DateTimeExtension.Configure( host.Services.GetRequiredService<IDateTimeDifference>() );我希望获得尽可能低的性能损失。
有没有办法强制我的扩展方法的用户在启动时调用Configure方法?
这段代码会被认为是可测试的吗?如何测试扩展方法?测试IDateTimeDifference接口的实现是否足够?
一般来说,扩展方法是解决这个问题的好方法,考虑到我不想在每个差异计算方法中传递IDateTimeDifference参数。
有没有其他更合适的注射方法?如果我不需要在运行时改变差异计算,依赖注入是必要的吗?
发布于 2021-04-12 02:04:47
TimeSpan结构https://docs.microsoft.com/en-us/dotnet/api/system.timespan?view=net-5.0来计算以日、月为单位的时间差吗? years?this对象。在为结构定义扩展方法时,它们不应该有任何其他外部dependency.https://stackoverflow.com/questions/67046998
复制相似问题