2014-03-06 86 views
18

更嚴格的我有如下因素類:訪問必須比屬性或索引

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Data.Odbc; 

namespace Framework 
{ 
    public class OracleProvider 
    { 
     private OdbcConnection db { get; private set; } 
     private String dbUsername = Settings.Default.Username; 
     private String dbPassword = Settings.Default.Password; 

     public OracleProvider() 
     { 
      connect(); 
     } 

     public void connect() 
     { 
      db = new OdbcConnection("Driver={Microsoft ODBC for Oracle};Server=CTIR; UID="+dbUsername+";PWD="+dbPassword+";");  
     }   
    } 
} 

現在我得到以下錯誤:

Error 11: The accessibility modifier of the 'Framework.OracleProvider.db.set' accessor must be more restrictive than the property or indexer 'Framework.OracleProvider.db'

我一直在尋找類似的問題,但避風港真的找不到答案。

任何人都可以向我解釋爲什麼會發生這種情況嗎?我真的很想學習。

回答

31

這就是問題所在:

private OdbcConnection db { get; private set; } 

假設你真的想都getter和setter是私有的,這應該是:

private OdbcConnection db { get; set; } 

設置器已經private,因爲這是整體財產的可及性。

或者,如果您希望getter是非私人的而setter是私人的,您需要指定其他修飾符,例如,

internal OdbcConnection db { get; set; } 

基本上,如果你要對財產的get;或部分指定訪問修飾符,它必須是更嚴格的比它本來是。

從C#規範的第10.7.2:

The accessor-modifier must declare an accessibility that is strictly more restrictive than the declared accessibility of the property or indexer itself. To be precise:

  • If the property or indexer has a declared accessibility of public , the accessor-modifier may be either protected internal , internal , protected , or private .
  • If the property or indexer has a declared accessibility of protected internal , the accessor-modifier may be either internal , protected , or private .
  • If the property or indexer has a declared accessibility of internal or protected , the accessor-modifier must be private .
  • If the property or indexer has a declared accessibility of private , no accessor-modifier may be used.

(順便說一句,如果是私密的讀取和寫入,它很可能是隻是爲了更好地使用領域大部分收益。使用屬性的僅存在,如果它暴露超過當前的類。如果你把它作爲一個屬性,考慮重新命名它遵循正常的.NET命名約定。)

+0

一個常見的模式就是讓二傳手私人但吸氣公共/爲了使財產保護只讀,可能值得添加這個答案只是爲了完整 – Charleh

+0

@Charleh:我已經這樣做了,給出了一個內部getter的例子。 –

+0

是的,我的評論花了大約5分鐘時間,你已經更新了:) – Charleh

6

好了,這個錯誤告訴所有所需信息

accessibility modifier ... accessor must be more restrictive than the property ...

private OdbcConnection db { // <- property as whole is "private" 
    get; 
    private set; // <- accessor (set) is explictly declared as "private" 
    } 

所以你可以做任何

// property as a whole is "public", but "set" accessor is "private" 
    // and so the accessor is more restrictive than the property 
    public OdbcConnection db { // <- property as whole is "public" 
    get; 
    private set; // <- accessor is "private" (more restrictive than "public") 
    } 

或者

private OdbcConnection db { 
    get; 
    set; // <- just don't declare accessor modifier 
    } 
相關問題