2017-02-18 44 views
1

如何在C#中声明和初始化F#中定义的歧视联盟值?如何在C#中声明并初始化F#中定义的歧视联盟值?

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)。

+5

从“new Events.NewBuyRequested”中删除新的。它现在有效。 –

回答

1

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

  • 对于所有工会的情况下有参数,F#编译器生成的名字"New"的静态方法加上工会例的名称。
  • 对于所有没有参数的联合事例,会生成一个静态只读属性,它与联合事件案例名称相同。

例如,在这个联盟,

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是识别他们的一个如来自工会案例,并包含wh的顺序他们被定义了。