2016-07-03 53 views
16

我正在寫一個小代碼,以便更加了解propertystatic property。像這些:c#中的靜態屬性6

class UserIdentity 
{ 
    public static IDictionary<string, DateTime> OnlineUsers { get; set; } 
    public UserIdentity() 
    { 
     OnlineUsers = new Dictionary<string, DateTime>(); 
    } 
} 

class UserIdentity 
{ 
    public IDictionary<string, DateTime> OnlineUsers { get; } 
    public UserIdentity() 
    { 
     OnlineUsers = new Dictionary<string, DateTime>(); 
    } 
} 

因爲我把它改爲:

class UserIdentity 
{ 
    public static IDictionary<string, DateTime> OnlineUsers { get; } 
    public UserIdentity() 
    { 
     OnlineUsers = new Dictionary<string, DateTime>(); 
    } 
} 

它給了我錯誤消息:

屬性或索引「UserIdentity.OnlineUsers '不能分配給 - 它只能讀取

我知道財產OnlineUsersread only,但在C#6中,我可以通過構造函數分配它。那麼,我錯過了什麼?

回答

26

您試圖在實例構造函數中分配給只讀靜態屬性。這會在每次創建新實例時導致它被分配,這意味着它不是隻讀的。你需要分配給它的靜態構造函數:

public static IDictionary<string, DateTime> OnlineUsers { get; } 

static UserIdentity() 
{ 
    OnlineUsers = new Dictionary<string, DateTime>(); 
} 

或者你也可以做內聯:

所有的
public static IDictionary<string, DateTime> OnlineUsers { get; } = new Dictionary<string, DateTime>(); 
+2

的問題也發生在C#1.0起(仿製藥除外),只是用不同的語法聲明OnlineUsers –

+1

@ MartinCapodici:然後,它必須是一個字段,而不是一個屬性,因爲你不能擁有一個「只讀屬性,你也可以分配給」,這是在C#6中添加的。 –

+0

馬蒂,那是真的我是想着用財產包裝的領域達到相同的效果。 –

8

首先,你的構造函數缺少括號()。正確的構造是這樣的:

public class UserIdentity { 

    public UserIdentity() { 
     ... 
    } 
} 

對於你的問題: 只讀屬性只能在特定的上下文的構造進行分配。一個static屬性未綁定到特定實例,而是綁定到該類。

在你的第二個代碼片段OnlineUsers是非靜態的,因此它可以分配給新實例的構造函數,並且只在那裏。

在您的第三個片段中,OnlineUsers是靜態的。因此,它只能分配給靜態初始化器。

class UserIdentity 
{ 
    public static IDictionary<string, DateTime> OnlineUsers { get; } 

    //This is a static initializer, which is called when the first reference to this class is made and can be used to initialize the statics of the class 
    static UserIdentity() 
    { 
     OnlineUsers = new Dictionary<string, DateTime>(); 
    } 
} 
2

靜態只讀屬性,必須在靜態構造函數可以這樣分配:

public static class UserIdentity 
{ 
    public static IDictionary<string, DateTime> OnlineUsers { get; } 

    static UserIdentity() 
    { 
     OnlineUsers = new Dictionary<string, DateTime>(); 
    } 
}