我遇到了这个问题的公认答案 about dealing with DateTime.Now in unit tests其中包含以下代码示例:
private readonly Func<DateTime> _nowProvider;
public SomeClass(Func<DateTime> nowProvider)
{
_nowProvider = nowProvider;
}
public bool Foo()
{
return (_nowProvider().DayOfWeek == DayOfWeek.Sunday);
}
这样实例化:
var s = new SomeClass(() => DateTime.Now);
我没怎么用过Func<T>
在 C# 中,所以我想我会看看 at the Microsoft documentation for it其中有以下评论:
You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have no parameters and must return a value.
为什么在示例中传递 Func<DateTime>
会更有益? , 实例化为 Class(() => DateTime.Now)
给构造函数
而不是简单地传入 DateTime
参数实例化为 Class(DateTime.Now)
给构造函数?
根据上面提到的 Microsoft 文档,LINQ lambda 构造函数也采用 Func<T>
争论和我的经验证明它们非常灵活,但我不明白为什么?
最佳答案
Rather than to just simply pass in a DateTime parameter instantiated as Class(DateTime.Now) to the constructor?
因为该值应该是当前的日期时间,而不是实例化该类时的日期时间。
当代码运行时,Func 返回代码执行时的日期。
如果将 DateTime 存储在一个字段中,它将是创建时间,而不是现在。
我有一个例子。
假设您在星期六的 23:59:55 创建了 Class
的实例。
10 秒后,以下内容被截断:
(passedDateTime.DayOfWeek == DayOfWeek.Sunday);
会返回 false。
对于提供程序,日期时间实际上是星期日 - 它执行的时间。
技术:
DateTime 是一个结构。
将 DateTime 作为参数传递给方法或构造函数时,它是作为值而不是引用传递的。
因此 DateTime
不会是最新的,而只是值的快照。
你可以自己确认一下:
var dateTime = DateTime.Now;
System.Threading.Sleep(1000);
bool equals = dateTime == DateTime.Now; // false
关于c# - 为什么将 func<T> 传递给构造函数而不是 T?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45374180/