【问题标题】:Need help converting C# to F#需要帮助将 C# 转换为 F#
【发布时间】:2021-03-08 17:59:30
【问题描述】:

我想知道如何将这段代码逐行从 C# 转换为 F#。我不打算使用任何 F# 的习语或类似的东西。我正在尝试了解如何在 F# 中枚举和反射。

using System.Linq;

namespace System.Collections.Generic
{
    public static class EnumerableExtensions
    {
        private static readonly Random random;
        static EnumerableExtensions()
        {
            random = new Random();
        }
        public static T Random<T>(this IEnumerable<T> input)
        {
            return input.ElementAt(random.Next(input.Count()));
        }
    }
}

【问题讨论】:

  • 您的随机变量应该具有[ThreadStatic] 作为属性,以使代码在多线程情况下安全。

标签: f#


【解决方案1】:

您可以将扩展定义为类型中的静态方法,但您必须使用Extension 属性标记它们。直接重写您的 C# 代码将是:

open System.Runtime.CompilerServices

[<Extension>]
type EnumerableExtensions() =
  static let rnd = System.Random()
  [<Extension>]
  static member Random(input:seq<_>) = 
    input |> Seq.item (rnd.Next(Seq.length input))

[1;2;3].Random()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-17
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多