简体   繁体   English

如何比较 f# 可区分联合实例的相等性?

[英]How to compare equality of f# discriminated union instances?

A month ago I asked that question about how to fulfill business rules with F# types.一个月前,我问了一个关于如何使用 F# 类型实现业务规则的问题

The given answer worked well for me but when working with the type I struggled by comparing two instances of that type.给定的答案对我来说效果很好,但是在使用该类型时,我通过比较该类型的两个实例而苦苦挣扎。

Here´s the implementation again:下面是实现:

    [<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

Because it´s used as an identifier I always have to compare two instances.因为它被用作标识符,所以我总是必须比较两个实例。
code in C# 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()))
{
    ...
}

I tried to override == operators but i couldn´t do it because the internal value is not just a simple field.我试图覆盖==运算符,但我无法做到,因为内部值不仅仅是一个简单的字段。
Is it possible to get to my wanted behavior?是否有可能达到我想要的行为? Thanks for your help!谢谢你的帮助!

F# unions are .NET sealed classes with implemented structural compare by default, but they don't overrite the '==' operators. F# 联合是默认情况下实现结构比较的 .NET 密封类,但它们不会覆盖“==”运算符。

Check the representation of the F# classes in C# . 检查 F# 类在 C# 中的表示 You can see how the .Equal method is implemented.您可以看到.Equal方法是如何实现的。

What you can do is你能做的是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM