2016-07-03 4 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>(); 
    } 
} 

プロパティまたはインデクサ「UserIdentity.OnlineUsers:

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

は、それは私にエラーメッセージを与えました'を割り当てることはできません - それは読み取り専用です

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

問題もOnlineUsers –

+1

を宣言するためだけの別の構文で、以降はC#1.0(脇ジェネリック)に起こるでしょう@ MartinCapodici:C#6で追加された「読み込み専用のプロパティ」を持つことができないため、フィールドでなくプロパティでなければなりません。 –

+0

Matti、それは本当です同じ効果を達成するためにプロパティでラップされたフィールドを考える。 –

8

まず、あなたのコンストラクタはカッコ()が欠落しています。正しいコンストラクタは次のようになります。あなたの質問のために

public class UserIdentity { 

    public UserIdentity() { 
     ... 
    } 
} 

: 読み取り専用のプロパティは、特定のコンテキストのコンストラクタに割り当てることができます。 staticプロパティは、特定のインスタンスではなくクラスにバインドされています。

2番目のコードスニペットOnlineUsersは静的ではないため、新しいインスタンスのコンストラクタ内でのみ割り当てることができます。

3番目のスニペットでは、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>(); 
    } 
} 
関連する問題