[英]Properly implement F# Unit in C#
This question is not about C#\/F# compatibility as in this one<\/a> .这个问题与这个<\/a>问题中的 C#\/F# 兼容性无关。
I'd like to know the proper way to implement a type like F# Unit<\/a> in place of using void<\/code> .
我想知道实现
F# Unit<\/a>之类的类型而不是使用
void<\/code>的正确方法。
Wondering if an empty class could impersonate this role.想知道一个空类是否可以扮演这个角色。
internal class Unit
{
}
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
的实现:
prim-types.fsi
公共接口在prim-types.fsi
定义prim-types.fs
prim-types.fs
提供了实现Here are the key points about the F# unit
implementation以下是有关 F# unit
实现的要点
GetHashCode
and Equals
in the same way to the Rx version它以与 Rx 版本相同的方式实现GetHashCode
和Equals
IComparable
and all values of the unit
type are equal它是IComparable
并且unit
类型的所有值都相等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.Default
或null
(因此它不是真正的单位!)
System.ValueTuple
(without generic argument) is very much unit in C#. System.ValueTuple
(不带泛型参数)在 C# 中是非常重要的单元。 The source code is open. 源代码是开放的。
I have used this Unit type as a reference: https:\/\/github.com\/louthy\/language-ext\/blob\/main\/LanguageExt.Core\/DataTypes\/Unit\/Unit.cs<\/a>我已将此 Unit 类型用作参考: https<\/a> :\/\/github.com\/louthy\/language-ext\/blob\/main\/LanguageExt.Core\/DataTypes\/Unit\/Unit.cs
Coming from a functional extension library.来自功能扩展库。
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.