c# - 在公共(public)属性 getter 中使用私有(private)变量

标签 c# properties

如果我有一个只有 getter 的公共(public)属性,使用私有(private)变量赋值然后返回该值是否正确,或者我应该只使用 return 而不是设置值用户ID?将来我们计划添加更多使用 userID 字段的功能,并且将向此类添加使用 userID 字段的方法。一种或另一种方式有什么好处吗?有没有其他方法可以做到这一点?

    private string userID;
    public string ID
    {
        get
        {
            if (System.Web.HttpContext.Current.Request.Headers.AllKeys.Contains("UID"))
            {
                userID = System.Web.HttpContext.Current.Request.Headers["UID"].ToString();
            }
            else
            {
                userID = "0000";
            }
            return userID;
        }
    }

最佳答案

getter 现在的编码方式不需要赋值,因为后续调用会忽略之前方法设置的值。但是,您可以像这样缓存结果:

private string userID;
public string ID {
    get {
        if (userID == null) {
            if (System.Web.HttpContext.Current.Request.Headers.AllKeys.Contains("UID")) {
                userID = System.Web.HttpContext.Current.Request.Headers["UID"].ToString();
            } else {
                userID = "0000";
            }
        }
        return userID;
    }
}

此实现通过将初始检索结果缓存在私有(private)实例变量中,避免重复读取 “UID”

关于c# - 在公共(public)属性 getter 中使用私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16463879/

相关文章:

javascript - 为什么标记位置对象更改纬度和经度属性名称

c# - 如何防止 WebMethod 序列化 json 响应

delphi - 让 getter 返回私有(private) var 属性的值

c# - 从其他窗口获取 ListView 项目

c# - Julian 时间戳到日期时间

java - 可观察/列表或属性 : exception thrown in listener not "seen" by unit test

xml - gwt.xml 中可能的 user.agent 值是什么?

wpf - 当文本框中未填写任何内容时,将 null 设置为 mvvm WPF 中的属性

c# - 在 C# 中以字节为单位查找对象实例的大小

c# - 在 NodeJS 中模拟 C# 溢出