2017-03-01 60 views
2
[<Extension>] 
static member ToOrganizationRequest<'T when 'T :> OrganizationRequest> (entity: Entity) = 
    let request = Activator.CreateInstance(typeof<'T>) :?> OrganizationRequest 
    request.Parameters.Item "Target" <- entity 
    request 

[<Extension>] 
static member ToOrganizationRequest<'T when 'T :> OrganizationRequest> (entities: seq<Entity>) = 
    entities 
    |> Seq.map (fun x -> x.ToOrganizationRequest<'T>()) 

第二extensionmethod不能引用該第一,所以F#的一種擴展方法,參考另一

|> Seq.map(樂趣X - > x.ToOrganizationRequest <「T>())

失敗,因爲我不能使用ToOrganizationRequest。 有什麼辦法讓它理解參考?

+5

靜態成員可以通過'TypeName.StaticMember'獲得,所以嘗試使用它來代替'this.StaticMember'。 –

+0

你是什麼意思?我應該能夠做一些像Entity.ToOrganizationRequest <'T>?因爲我無法做到這一點。 –

回答

7

如果你不需要你的擴展方法是在C#中可見,可以(並且可能應該)延長Entity型這樣,而不是:

type Entity with 
    member this.ToOrganizationRequest<'T when 'T :> OrganizationRequest>() = 
     let request = Activator.CreateInstance(typeof<'T>) :?> OrganizationRequest 
     request.Parameters.Item "Target" <- entity 
     request 

這將使你的第二個C#風格的擴展方法充當您最初寫的:如果你需要他們在C#

[<Extension>] 
type Ext = 
    [<Extension>] 
    static member ToOrganizationRequest<'T when 'T :> OrganizationRequest> (entities: seq<Entity>) = 
     entities 
     |> Seq.map (fun x -> x.ToOrganizationRequest<'T>()) 

,你必須將擴展方法中定義的類型中靜態調用其他擴展方法。

[<Extension>] 
type Ext = 
    [<Extension>] 
    static member ToOrganizationRequest<'T when 'T :> OrganizationRequest> (entity: Entity) = 
     let request = Activator.CreateInstance(typeof<'T>) :?> OrganizationRequest 
     request.Parameters.Item "Target" <- entity 
     request 

    [<Extension>] 
    static member ToOrganizationRequest<'T when 'T :> OrganizationRequest> (entities: seq<Entity>) = 
     entities 
     |> Seq.map (Ext.ToOrganizationRequest) 

您可以在F#文檔here內詳細瞭解各種類型的擴展方法。

+0

我打電話從C#代碼。完美的工作,非常感謝你! –

+2

其實@TheInnerLight F#風格的擴展方法不適用於第二種方法,因爲'this'應該是'seq ';你需要編寫'輸入seq ...',這是不允許的。 – Tarmil

+0

@Tarmil謝謝,我認爲這個故事的寓意是不要在匆忙中寫下答案:) – TheInnerLight