我正在开发一个依赖于日期时间的应用程序(一个 Web 应用程序、asp.net 和 c#),因此,它会根据当前日期启动表单供登录用户填写。
我一直在考虑我们将如何模拟应用程序的实际使用情况,以便进行调试和测试。
所以我说的是替换所有这些:
DateTime currentDate = DateTime.Now;
用类似的东西:
DateTime currentDate = MyDateClass.GetCurrentDate();
然后我会上课:
public class MyDateClass
{
private DateTime _currentDate;
public DateTime GetCurrentDate()
{
// get the date, which may be different from DateTime.Now
return _currentDate;
}
public void SetCurrentDate(DateTime newCurrentDate)
{
// set the date to the value chosen by the user
_currentDate = newCurrentDate;
}
}
允许我通过调用 SetCurrentDate 方法来设置当前数据,例如,在链接按钮和日历输入的代码隐藏中。
问题是……我应该如何在整个应用程序中准确地存储 DateTime 变量?我不能在这节课上学习,对吧?我应该使用线程吗?
嗯,非常感谢您的想法 :) 在此先感谢您的建议!
关于我的问题的一些更新:
我遇到了这个帖子:What's a good way to overwrite DateTime.Now during testing?
就像您在这里提供的答案一样(谢谢!),良好代码组织的重要提示,用于开发和测试目的,我肯定会在接下来的时间考虑。
但我仍然有同样的问题:我将如何“保存”日期时间值?
现在,我开始在数据库中创建一个单元格表来维护“我的”日期时间值。
我有一个带有 GetCurrentDate 和 SetCurrentDate 函数的静态类:
public static class DateManagement
{
public static DateTime GetCurrentDate()
{
// return DateTime.Now;
// OR:
// ...
// SqlCommand cmd = new SqlCommand("select Date from CurrentDate", conn);
// ...
}
public static void SetCurrentDate(DateTime newDate) // used only in debugging
{
// ...
// string insertStr = @"update CurrentDate set Date = '" + date + "'";
// SqlCommand cmd = new SqlCommand(insertStr, conn);
// ...
}
}
但是,将日期存储在数据库中,创建一个表并仅用于调试,这似乎不是一个优雅的解决方案...
请您参考如下方法:
创建接口(interface):
public interface ITimeProvider
{
DateTime Now { get; }
}
然后您可以创建两个子类 - 一个用于生产用途,它仅使用 DateTime.Now 返回当前时间,另一个您可以手动设置时间用于测试目的。使用 dependency injection提供适当的实现。
