static property in c# 6

白昼怎懂夜的黑 提交于 2019-11-30 14:41:51

问题


I'm writing a small code to more understand about property and static property. Like these:

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

or

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

Since I changed it to:

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

it gave me error message:

Property or indexer 'UserIdentity.OnlineUsers' cannot be assigned to -- it is read only

I knew the property OnlineUsers was read only, but in C# 6, I can assign it via constructor. So, what am I missing?


回答1:


You're trying to assign to a read only static property in an instance constructor. That would cause it to be assigned every time a new instance is created, which would mean it's not read only. You need to assign to it in the static constructor:

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

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

Or you can just do it inline:

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



回答2:


First of all, your constructors are missing the parenthesis (). A correct constructor looks like this:

public class UserIdentity {

     public UserIdentity() {
        ...
     }
}

For your question: Readonly properties can only be assigned in the constructor of the specific context. A static property is not bound to a specific instance but to the class.

In your second code snippet OnlineUsers is non static, thus it can be assigned to in the constructor of a new instance, and only there.

In your third snippet, OnlineUsers is static. Thus, it can only be assigned to in a static initializer.

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>();
    }
}



回答3:


Static readonly property must be assigned in static constructor like this:

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

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


来源:https://stackoverflow.com/questions/38170840/static-property-in-c-sharp-6

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!