C#6中的静态属性 [英] static property in c# 6

查看:51
本文介绍了C#6中的静态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一小段代码,以进一步了解属性静态属性.像这样:

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

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'不能分配给它-只读的

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

我知道属性 OnlineUsers 只读,但是在C#6中,我可以通过构造函数进行分配.所以,我想念什么?

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

推荐答案

您正在尝试将其分配给实例构造函数中的只读静态属性.这将导致在每次创建新实例时对其进行分配,这意味着它不是只读的.您需要在静态构造函数中为其分配:

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

或者您也可以内联:

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

这篇关于C#6中的静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆