我正在尝试添加一个扩展方法,该方法生成一个随机的整数HashSet,用于NBuilder模拟库。
这是我想简化为简单扩展方法的方法:
using System;
using FizzWare.NBuilder;
using System.Collections.Generic;
using System.Linq;
namespace FakeData
{
public class Person
{
public string Name { get; set; }
public HashSet<int> AssociatedIds { get; set; }
}
class Program
{
static void Main(string[] args)
{
var people = Builder<Person>.CreateListOfSize(50)
.All()
.With(p => p.AssociatedIds =
Enumerable.Range(0, 50)
.Select(x => new Tuple<int, int>(new Random().Next(1, 1000), x))
.OrderBy(x => x.Item1)
.Take(new Random().Next(1, 50))
.Select(x => x.Item2)
.ToHashSet())
.Build();
}
}
}
我想替换With()
,所以它看起来像:
var people = Builder<Person>.CreateListOfSize(50)
.All()
.RandomHashInt(p => p.AssociatedIds, 1, 50)
.Build();
这样的事情:
public static IOperable<T> RandonHashInt<T>(this IOperable<T> record, Expression<Func<T, HashSet<int>>> property, int min, int max)
{
//add hashset
return record;
}
有人能指出我正确的方向吗
答案 0 :(得分:1)
我查看了NBuilder With()
方法的源代码,并复制了它在那里完成的方式:
public static IOperable<T> WithRandonHashInt<T>(this IOperable<T> record, Expression<Func<T, HashSet<int>>> property, int min, int max)
{
var declaration = record as IDeclaration<T>;
var rand = new Random();
declaration.ObjectBuilder.With(property,
Enumerable.Range(min, max)
.OrderBy(e => Guid.NewGuid().GetHashCode())
.Take(rand.Next(min, max))
.ToHashSet());
return (IOperable<T>)declaration;
}