2015-09-09 65 views
9

我有這個類:有沒有辦法在二級構造函數中設置自動屬性?

type Sample() = 
    member val test1 = "" with get,set 
    member val test2 = "" with get,set 

    // is something like the below constructor possible 
    new Sample(result1, result2) = 
     this.test1 <- "failed" 
     this.test2 <- "passed" 
     Sample() 

我試過幾種不同的方式,但我不能得到它的工作。

回答

5

@馬克西曼的答案是正確的解決方案,但你可以得到正是你想要使用的是什麼這個奇怪的建築:

type Sample() = 
    member val test1 = "" with get,set 
    member val test2 = "" with get,set 

    new (result1, result2) as sample = 
     Sample() 
      then 
       sample.test1 <- result1 
       sample.test2 <- result2 

但說實話,這是我從來沒有用過的東西,可能從來沒有見過用在野外,更多的是一種語言瑣事,而不是其他任何東西。

+0

它編譯,但它不會做我所期望的... –

+0

呵呵。我想這是因爲沒有使用參數(這也是OP的代碼所做的)。 – scrwtp

+1

@Mark Seemann,對不起,你期望它做什麼? https://dotnetfiddle.net/wq711M –

6

這是你想要的嗎?

type Sample(result1, result2) = 
    member val Test1 = result1 with get,set 
    member val Test2 = result2 with get,set 
    new() = Sample("failed", "passed") 

FSI:

> Sample();; 
val it : Sample = FSI_0002+Sample {Test1 = "failed"; 
            Test2 = "passed";} 
> Sample("foo", "bar");; 
val it : Sample = FSI_0002+Sample {Test1 = "foo"; 
            Test2 = "bar";} 
+1

嗯,我知道它可以在主構造函數中這樣做,但我只是好奇它是否有可能以相反的方式。 – user1206480

相關問題