2014-03-06 62 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 
    } 
相关问题