gpt4 book ai didi

c# - 如何使用 FsCheck 为可为 null 的类型生成 null?

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:22 24 4
gpt4 key购买 nike

我有这个似乎可以工作的生成器,但是当我检查生成的值时,它永远不会选择空值。如何编写一个将选择空值的生成器。此代码从不为“结束”日期选择空值。

public static Gen<DateTime?> NullableDateTimeGen()
{
var list = new List<DateTime?>();

if (list.Any() == false)
{
var endDate = DateTime.Now.AddDays(5);
var startDate = DateTime.Now.AddDays(-10);

list.AddRange(Enumerable.Range(0, 1 + endDate.Subtract(startDate).Days)
.Select(offset => startDate.AddDays(offset))
.Cast<DateTime?>()
.ToList());

list.Add(null);
list.Insert(0, null);
}

return from i in Gen.Choose(0, list.Count - 1)
select list[i];
}

public static Arbitrary<Tuple<DateRange, DateTime>> TestTuple()
{
return (from s in NullableDateTimeGen().Where(x => x != null)
from e in NullableDateTimeGen()
from p in NullableDateTimeGen().Where(x => x != null)
where s <= e
select new Tuple<DateRange, DateTime>(new DateRange(s.Value, e), p.Value))
.ToArbitrary();
}

最佳答案

问题与 FsCheck 无关,在这个声明中:

from s in NullableDateTimeGen().Where(x => x != null)
from e in NullableDateTimeGen()
from p in NullableDateTimeGen().Where(x => x != null)
where s <= e
select new Tuple<DateRange, DateTime>(new DateRange(s.Value, e), p.Value))

请注意,您从 sp 中过滤了 null,因此它们永远不会为 null。 if e 唯一可以为 null 的东西。但是,你这样做

where s <= e

如果 e 为 null,则此比较永远不会为真,因为与 null 进行比较的任何内容始终为 false。因此,您还过滤掉了 e 的空值。

要解决这个问题,只需将该条件替换为对您的场景有意义的任何内容,例如

where e == null || s <= e

关于c# - 如何使用 FsCheck 为可为 null 的类型生成 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42771356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com