Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

Initialize instance of internal discriminated union from F# to C#

I have a discriminated union type exported via a dll from F# to be used in C#:

type Argument =
  | IntValue
  | FloatValue
  | BoolValue of bool

In C# I can initialize something like Argument.NewBoolValue(true), but the other two types IntValue and FloatValue are not type generated via the F# compiler and hence marked as internal, is there a way to initialize them in C#?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If the discriminated union case doesn't have any payload, there is no NewXXX method generated. Because all instances of such union case will be the same and there is no need in creation function. So use staic properties instead

Argument.IntValue
Argument.FloatValue

Internally these properties just return singleton instance of corresponding usecase:

internal static readonly Argument _unique_IntValue = new _IntValue();

public static Argument IntValue => _unique_IntValue;

More interesting details can be observed in this decompiled snippet.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...