【发布时间】: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