F #

2012-11-25 4 views
18

에 out 매개 변수가있는 멤버를 만드는 방법 F #에서 F #에서 사용할 때 out 매개 변수를 결과 튜플의 멤버로 처리 할 수 ​​있음을 알고 있습니다. 내가 out 매개 변수를 가진 것으로 C 번호에 나타납니다 서명을해야하는 멤버를 정의하는 방법F #

(success, i) = System.Int32.TryParse(myStr) 

는 내가 알고 싶은 것은.

가능합니까? 그리고 난 그냥 튜플을 반환하고 C#에서 메서드를 호출 할 때 반대 프로세스가 발생할 수 있습니다.

type Example() = 
    member x.TryParse(s: string, success: bool byref) 
    = (false, Unchecked.defaultof<Example>) 

답변

18

없음 , 당신은 튜플로 결과를 반환 할 수 없습니다 - 당신은 함수에서 결과를 반환하기 전에하는 ByRef 값으로 값을 할당해야합니다. 또한 [<Out>] 속성을 주목하십시오.이 속성을 생략하면 매개 변수는 C# ref 매개 변수처럼 작동합니다.

open System.Runtime.InteropServices 

type Foo() = 
    static member TryParse (str : string, [<Out>] success : byref<bool>) : Foo = 
     // Manually assign the 'success' value before returning 
     success <- false 

     // Return some result value 
     // TODO 
     raise <| System.NotImplementedException "Foo.TryParse" 

당신이 당신의 방법은 표준 C#을 Try 서명을 할 경우 (예를 들어, Int32.TryParse가), 당신은 당신의 방법에서 bool을 반환하고 통과해야 다시 byref<'T>을 통해 Foo을 가능하게 구문 분석과 같이 :

open System.Runtime.InteropServices 

type Foo() = 
    static member TryParse (str : string, [<Out>] result : byref<Foo>) : bool = 
     // Try to parse the Foo from the string 
     // If successful, assign the parsed Foo to 'result' 
     // TODO 

     // Return a bool indicating whether parsing was successful. 
     // TODO 
     raise <| System.NotImplementedException "Foo.TryParse" 
4
open System.Runtime.InteropServices 

type Test() = 
    member this.TryParse(text : string, [<Out>] success : byref<bool>) : bool = 
     success <- false 
     false 
let ok, res = Test().TryParse("123")