简体   繁体   English

在 C# 中正确实现 F# Unit

[英]Properly implement F# Unit in C#

I'm not sure what is the best way to define Unit for usage from C#.我不确定从 C# 定义Unit以供使用的最佳方法是什么。 It might differ from how this is done in F# (because in F#, the compiler hides the usage in a way).它可能与 F# 中的做法不同(因为在 F# 中,编译器以某种方式隐藏了用法)。

However, you can actually find the implementation of F# unit in the core library:但是,您实际上可以在核心库中找到 F# unit的实现:

Here are the key points about the F# unit implementation以下是有关 F# unit实现的要点

  • It implements GetHashCode and Equals in the same way to the Rx version它以与 Rx 版本相同的方式实现GetHashCodeEquals
  • It is IComparable and all values of the unit type are equal它是IComparable并且unit类型的所有值都相等
  • Most importantly, it has a private constructor and so you cannot create a new unit value.最重要的是,它有一个私有构造函数,所以你不能创建一个新的unit值。 It also has no default instance (unlike the Rx unit) and so in F#, all unit values are actually represented as null .它也没有默认实例(与 Rx 单元不同),因此在 F# 中,所有单元值实际上都表示为null However, the language/compiler generally hide this fact.但是,语言/编译器通常会隐藏这一事实。

So, it sounds like the only difference in F# is that it uses the null value.因此,听起来 F# 中的唯一区别是它使用null值。 If you want to use unit explicitly, this might not be the best choice.如果您想明确使用unit ,这可能不是最佳选择。 However, if you have Unit.Default then you are ultimately defining a type with two possible values, because it can be either Unit.Default or null (and so it is not really a unit!)但是,如果您有Unit.Default那么您最终会定义一个具有两个可能值的类型,因为它可以是Unit.Defaultnull (因此它不是真正的单位!)

System.ValueTuple (without generic argument) is very much unit in C#. System.ValueTuple (不带泛型参数)在 C# 中是非常重要的单元 The source code is open. 源代码是开放的。

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

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