2014-03-06 5 views
4

더 클래스 :선택적 매개 변수

type NotAbstract = 
    class 
    new : unit -> NotAbstract 
    member WithOptionalParameters : x:int * ?y:int -> int 
    end 

그러나이 작동하지 않습니다 :

[<AbstractClass>] 
type AbstractExample() = 
    abstract WithOptionalParameters: int * ?int -> int /// Ouch... 

type NotAbstract() = 
    inherit AbstractExample() 
    override this.WithOptionalParameters (x, ?y) = 
     let y = defaultArg y 10 
     x + y 

하는 방법을 쓸 수

type NotAbstract() = 
    member this.WithOptionalParameters (x, ?y) = 
     let y = defaultArg y 10 
     x + y 

는 다음과 같은 유형의 서명이 선택적 매개 변수가있는 함수의 추상 정의에 적절한 유형 서명? 나는 어떤 힌트도 찾지 못했다 here.

PS : 나는 (비슷한) 결과가 polymorphism

+0

F # 방식 Nullable 유형 대신 (더 원시적 인) Option 유형을 사용하는 것입니다. –

답변

6

옵션 형식으로 인수를 선언 정말 인수는 선택하지 않습니다.

[<AbstractClass>] 
type AbstractExample() = 
    abstract WithOptionalParameters: int * ?y:int -> int  

type NotAbstract() = 
    inherit AbstractExample() 
    override this.WithOptionalParameters (x, ?y) = 
     let y = defaultArg y 10 
     x + y 

NotAbstract().WithOptionalParameters(42) // val it : int = 52 
따라서 추상적 회원 서명에 선택적 인수를 명명 static member OneNormalTwoOptional : arg1:int * ?arg2:int * ?arg3:int -> int

:

NotAbstract().WithOptionalParameters(2) 
// This expression was expected to have type 
//  int * Option<int>  
// but here has type 
//  int  

spec §8.13.6가 가지고 다음과 같이 서명에

를 선택적 인수가 나타납니다

2

을 달성 할 수 있다는 것을 알고이 작동합니다 :

[<AbstractClass>] 
type AbstractExample() = 
    abstract WithOptionalParameters: int * Nullable<int> -> unit 

In F#, there's no syntactical sugar for nullable types을, 당신은 ?y 구문으로 값이 널 (NULL)을 선언 할 수 있지만 있도록 , 유형에 대해서는 그렇게 할 수 없습니다. 대신 Nullable<T>을 사용해야합니다.

+0

s/선언 * 값 * nullable/선언 옵션 값 /? –

+0

원래의 질문을 잘못 읽었거나 다른인지 오류를 일으켰지 만, 이것이 해결책이라고 생각하게되었습니다. 분명히 올바른 대답은 polkduran이 제공하는 답변이지만, 나는 그 대답을 다른 사람을 도울 수있는 기회에 남겨 두겠다고 생각했다. –

+1

@Mark F #의'? arg' 구문은 "값을 nullable로 만듭니다." F # 클라이언트의 경우 튜플 된 메서드 매개 변수의 요소를 선택적으로 선언합니다. 그러나, F #가 아닌 클라이언트는 이것을'FSharpOption <...>'로 볼 것입니다. 이것은 F #을 포함하여 모든 CLI 클라이언트에 Nullable <...>으로 나타나는 값 유형을 nullable로 선언하는 C#의'? Type' 구문과 다릅니다. 두 개념은 서로 관련이 없습니다 ... –

4

선택적 매개 변수가 Option 유형 컴파일, ?int 대신 Option<int>를 사용

[<AbstractClass>] 
type AbstractExample() = 
    abstract WithOptionalParameters: int * Option<int> -> int  

type NotAbstract() = 
    inherit AbstractExample() 
    override this.WithOptionalParameters (x, ?y) = 
     let y = defaultArg y 10 
     x + y 
+0

고마워, 네, 맞습니다. 나는 실제로'int'를 반환하는'WithOptionalParameters'의 타입 시그니처에 내 자신의 에러를 수정하기 위해 답을 편집했습니다. – NoIdeaHowToFixThis

+0

@ NoIdeaHowToFixThis 편집 해 주셔서 감사합니다. 붙여 넣기 전에 코드를 확인하지 마십시오. – polkduran