如何比较 f# discriminated union 实例的相等性?

How to compare equality of f# discriminated union instances?

一个月前,我问 如何使用 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()))
{
    ...
}

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

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

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

你能做的是

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