【问题标题】:How to compare equality of f# discriminated union instances?如何比较 f# 可区分联合实例的相等性?
【发布时间】:2020-04-30 07:58:00
【问题描述】:

一个月前,我向that question 询问了如何使用 F# 类型实现业务规则。

给定的答案对我来说效果很好,但是在使用该类型时,我很难通过比较该类型的两个实例。

这里又是实现:

    [<AutoOpen>]
    module JobId =
        open System
        type JobId = private JobId of string with
            static member Create() = JobId(Guid.NewGuid().ToString("N"))

            static member Create(id:Guid) =
                if id = Guid.Empty then None
                else Some(JobId(id.ToString("N")))

            static member Create(id:string) =
                try JobId.Create(Guid(id))
                with :? FormatException -> None

        [<Extension>]
        type Extensions =
            [<Extension>]
            static member GetValue(jobId : JobId) : string =
                match jobId with
                | JobId.JobId id -> id

因为它被用作标识符,所以我总是需要比较两个实例。
C# 中的代码

IEnumerable<JobId> jobIds = await GetAllJobids();
JobId selectedJobId = GetSelectedJobId();

// that´s what I would like to do
if (jobIds.Any(id => id == selectedJobId))
{
    ...
}

// now I always have to compare the strings
if (jobIds.Any(id => id.GetValue() == selectedJobId.GetValue()))
{
    ...
}

我试图覆盖 == 运算符,但我做不到,因为内部值不仅仅是一个简单的字段。
是否有可能达到我想要的行为? 感谢您的帮助!

【问题讨论】:

    标签: c# functional-programming f# discriminated-union


    【解决方案1】:

    F# 联合是 .NET 密封类,默认实现结构比较,但它们不会覆盖“==”运算符。

    Check the representation of the F# classes in C#。可以看到.Equal方法是如何实现的。

    你能做的是

    if (jobIds.Any(id => id.Equals(selectedJobId))) {}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 2010-11-16
      相关资源
      最近更新 更多