如何在C#中声明和初始化F#中定义的Discriminated Union值?

时间:2017-02-18 08:00:14

标签: c# f#

如何在C#中声明和初始化F#中定义的Discriminated Union值?

F#代码:

namespace Core

[<AutoOpen>]
module EventStore =

    type Events =
        | BuyRequested  of RequestInfo
        | SellRequested of RequestInfo

RequestInfo定义如下:

namespace Core

[<AutoOpen>]
module Entities =
    type RequestInfo = { 
        AccountId : string
        Symbol    : string
        Quantity  : int 
    }

C#客户端:

var myEvent = new Events.NewBuyRequested(requestInfo); // Doesn't compile

我尝试引用此link,以便我可以参考下面的示例:

type Shape =
| Circle of float
| Rectangle of float * float

C#:

var circle = Shape.NewCircle(23.77);
var rectangle = Shape.NewRectangle(1.5, 2.2);

但是我没有看到任何针对我的DU案例值暴露的方法(即BuyRequested,SellRequested)。

1 个答案:

答案 0 :(得分:1)

正如您已经发现的那样,New...方法不是构造函数,而是静态方法。为了完整起见,我想补充以下内容:

  • 对于具有参数的所有联合案例,F#编译器生成名称为"New"的静态方法以及联合案例的名称。
  • 对于没有参数的所有联合案例,将生成一个静态只读属性,该属性与union案例具有相同的名称。

例如,在这个联盟中,

type U = 
    | U1
    | U2 of int

你得到:

> let members = typeof<U>.GetMembers();;
val members : System.Reflection.MemberInfo [] =
  [|U get_U1(); Boolean get_IsU1(); U NewU2(Int32); Boolean get_IsU2();
    Int32 get_Tag(); Int32 CompareTo(U); Int32 CompareTo(System.Object);
...

个别案例是:

> typeof<U>.GetMember("get_U1");;
val it : System.Reflection.MemberInfo [] =
  [|U get_U1()
      {Attributes = PrivateScope, Public, Static;
       CallingConvention = Standard;
       ContainsGenericParameters = false;
       CustomAttributes = seq [[Microsoft.FSharp.Core.CompilationMappingAttribute((Microsoft.FSharp.Core.SourceConstructFlags)8, (Int32)0)]];
...
> typeof<U>.GetMember("NewU2");;
val it : System.Reflection.MemberInfo [] =
  [|U NewU2(Int32)
      {Attributes = PrivateScope, Public, Static;
       CallingConvention = Standard;
       ContainsGenericParameters = false;
       CustomAttributes = seq [[Microsoft.FSharp.Core.CompilationMappingAttribute((Microsoft.FSharp.Core.SourceConstructFlags)8, (Int32)1)]];

CompilationMappingAttribute是将它们标识为来自联合案例的那个,并包含它们的定义顺序。

相关问题