【问题标题】:Defining extension method for fluent use定义流畅使用的扩展方法
【发布时间】:2018-07-30 14:36:24
【问题描述】:

我正在尝试添加一个扩展方法,该方法生成一个随机的整数 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;
}

有人能指点我正确的方向吗

【问题讨论】:

  • 您需要提供minimal reproducible example
  • 哪一部分不清楚?我展示了工作代码,然后展示了我需要添加代码的方法,但我需要帮助解决如何在record 中引用property。我不知道我怎样才能让它更清楚,但如果你告诉我哪一部分不清楚,我会尽力重写。
  • 我没有要求清楚。我要了minimal reproducible example。你读过那个链接吗?我希望能够复制、粘贴和编译您的代码。
  • 我确实读过它,但我误解了你的意图,我很抱歉。我以为你在说不清楚,。我添加了类和对问题的引用
  • 您能帮我复制、粘贴和编译您的代码吗?现在我做不到。

标签: c# linq .net-core fluent nbuilder


【解决方案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;
}

【讨论】:

  • 请不要在需要随机数的地方使用GuidGuids 不保证是随机的。它们保证是独一无二的。有区别。
  • 生成相同 Guid 的可能性很小。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-10
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多