更新时间:2023-02-16 10:14:30
100%的时间,如果我使用的是 DateTime
,我为此创建了一个接口。在进行测试的时候,这会使生活变得更加轻松。我相信这也会对您有用。
100% of the time, If I am using DateTime
, I create an interface for it. It just makes life a lot easier when it's time for testing. I believe this would work for you as well.
使用此方法有两个原因。
There's a couple of reasons for this method.
DateTime
的依赖关系。 MyAppDateTimeProvider
DateTime
out of your business logic.MyAppDateTimeProvider
public interface IDateTimeProvider
{
DateTime Now { get; }
string GetDateString(int year, int month, int day);
DateTime TryParse(string sqlDateString);
}
public class SqlDateTimeProvider : IDateTimeProvider
{
public DateTime Now => DateTime.UtcNow;
public string GetDateString(int year, int month, int day)
{
return new DateTime(year, month, day).ToString("yyyy-MM-dd");
}
public DateTime TryParse(string sqlDateString)
{
var result = new DateTime();
DateTime.TryParse(sqlDateString, out result);
return result;
}
}