2016-10-28 45 views

回答

2

根據

https://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.pureattribute(v=vs.110).aspx

PureAttribute屬性

表示一個類型或方法是純的,也就是說,它不作任何 可見狀態變化。

所以很有可能從這種方法拋出異常,例如,

// factorial is a pure function: no state will be changed, 
    // just a computation 
    [Pure] 
    public static BigInteger Factorial(BigInteger value) { 
    // We can't return infinity with BigInteger and that's why have to throw the exception 
    if (value < 0) 
     throw new ArgumentOutOfRangeException("value", "value must be non-negative"); 

    ... 
    } 

而如果我把這種純粹的方法

BigInteger result = Factorial(1000000000); 

可能的結果之一是OutOfMemory拋出異常

-2

我與梅德同意。

據MSDN文檔:

被稱爲合同內必須是純的所有方法;也就是說,他們不得更新任何先前存在的狀態。允許純方法修改在進入純方法後創建的對象。

允許拋出異常,並不一定被視爲改變對象狀態。

+4

你應該upvote而不是添加其他答案。 –

+0

爲什麼?我的回答並不是指同一篇文章?另一種信息可以從我的答案中找到。你不應該把它投下來。 – Diemauerdk

1

你可以拋出異常,你沒有做任何可見的狀態改變。這裏的例子從Reference source

[Pure] 
    private void VerifyWritable() { 
     if (isReadOnly) { 
      throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); 
     } 
     Contract.EndContractBlock(); 
    } 
相關問題