2012-04-18 65 views
0

我使用MVC3和NHibernate 我有一個類叫做激活碼像下面訪問:如何使私有財產MVC3

public virtual int LoginAccountId { get; set; } 
protected virtual string ActivatedCode { get; set; } 
protected virtual DateTime ActivationDate { get; set; } 

我想訪問控制器LIK這一領域

ActivationCode code=new ActivationCode(); 
code.ActivatedCode="abc"; 

但無法獲得它。爲什麼?

回答

1

該屬性爲protected這意味着您只能從類內部或其中一個繼承中訪問它。

public class ActivationCode{ 
    public virtual int LoginAccountId { get; set; } 
    protected virtual string ActivatedCode { get; set; } 
    protected virtual DateTime ActivationDate { get; set; } 

    public void Foo(){ 
     var x = this.ActivatedCode; // Valid 
    } 

}

public class Foo{ 
    new ActivationCode().ActivatedCode //Invalid access 
} 

你可以改變從protectedpublic的屬性,就像與LoginAccountId

閱讀MSDN文章關於protected

保護關鍵字是一個成員訪問修飾符。受保護的成員可以從聲明該類的類中進行訪問,也可以從派生於聲明該成員的類的任何類中進行訪問。

只有在通過派生類類型進行訪問時,才能在派生類中訪問基類的受保護成員。例如,請考慮下面的代碼段:

更新:

ActivationCode類應該是這樣的:

public class ActivationCode 
{ 
    public virtual int LoginAccountId { get; set; } 
    public virtual string ActivatedCode { get; set; } 
    public virtual DateTime ActivationDate { get; set; } 
} 
+0

那麼我怎麼能讓他們訪問?你能告訴我嗎? – priya77 2012-04-18 06:58:41

+1

@ priya77。我做了,從'protected'改爲'public' – gdoron 2012-04-18 06:59:17

+0

@ priya77。我添加了完整的代碼,你現在明白了嗎? – gdoron 2012-04-18 07:02:33

2

您不能從包含它們的類之外或派生類訪問受保護的成員。如果你沒有改變成員的可見性,那麼從ActivationCode類以外訪問它的唯一方法就是使用Reflection,但這絕對是可怕的。我會建議將其公開或公開一個公開的方法,以允許您修改其價值。

+0

:所以我可以讓他們如何進入?你能告訴我嗎? – priya77 2012-04-18 06:55:55

+0

你有沒有辦法做到這一點....喜歡使用私人而不是像這樣的保護或總結? – priya77 2012-04-18 06:58:13

+0

好的,謝謝...我會讓他們作爲公衆:) – priya77 2012-04-18 07:03:10