我正在编写一个小代码来更好地理解property和static property.像这些:
class UserIdentity
{
public static IDictionary<string, DateTime> OnlineUsers { get; set; }
public UserIdentity()
{
OnlineUsers = new Dictionary<string, DateTime>();
}
}
Run Code Online (Sandbox Code Playgroud)
要么
class UserIdentity
{
public IDictionary<string, DateTime> OnlineUsers { get; }
public UserIdentity()
{
OnlineUsers = new Dictionary<string, DateTime>();
}
}
Run Code Online (Sandbox Code Playgroud)
自从我改为:
class UserIdentity
{
public static IDictionary<string, DateTime> OnlineUsers { get; }
public UserIdentity()
{
OnlineUsers = new Dictionary<string, DateTime>();
}
}
Run Code Online (Sandbox Code Playgroud)
它给了我错误信息:
无法将属性或索引器"UserIdentity.OnlineUsers"分配给 - 它是只读的
我知道属性OnlineUsers是read only,但在C#6中,我可以通过构造函数分配它.那么,我错过了什么?
Mat*_*nen 27
您正尝试在实例构造函数中分配只读静态属性.这将导致每次创建新实例时都会分配它,这意味着它不是只读的.您需要在静态构造函数中为其分配:
public static IDictionary<string, DateTime> OnlineUsers { get; }
static UserIdentity()
{
OnlineUsers = new Dictionary<string, DateTime>();
}
Run Code Online (Sandbox Code Playgroud)
或者你可以直接进行:
public static IDictionary<string, DateTime> OnlineUsers { get; } = new Dictionary<string, DateTime>();
Run Code Online (Sandbox Code Playgroud)
首先,您的构造函数缺少括号().一个正确的构造函数如下所示:
public class UserIdentity {
public UserIdentity() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
对于您的问题:只能在特定上下文的构造函数中分配只读属性.一个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>();
}
}
Run Code Online (Sandbox Code Playgroud)