我已经编程好几个月了,在课堂上经常使用的一个词是“上下文”。比如ServletContext (Java), Activity (Android), Service (Java, Android), NSManagedContext (Objective-C, iOS)。

通过查字典,我知道这个词的意思是:处境,环境,情况等。然而,因为我的母语不是英语,我不知道我应该直接翻译成什么。例如,如果我要编写一个命名为SomeClassContext的类,或者一个具有上下文参数的方法,我就不知道什么时候应该将其命名为context,因为我不理解它。

我一直在Stack Overflow上搜索上下文,但没有问题/答案能够帮助我。

如果有人能给我解释一下,我将非常高兴。


当前回答

我总是认为上下文是与我正在处理的对象或结构相关的特定状态。

For example, when you are using drawRect in a view (where all drawing must be done for a view) you must always get the currentGraphicsContext into which you will issue your core graphics statements. This context contains things like bounds of the view, the stroke colour, the stroke thickness for drawing a line, the fill color for filling a closed Path etc. this context (like most others) is just the current state at this point in time. so think of the graphics context in this case as just a set of state such as

描边厚度为1.5像素 填充颜色为黑色 视界为(155,200) 笔画颜色为红色

它基本上是当前时间点的状态……

其他回答

上下文可以看作是传递信息的桶。它通常用于传递不一定直接绑定到方法调用的东西,但仍然可能是相关的。外行描述它的方式可能是“你可能关心的东西”。

例如,如果你正在编写一个服务来更新db中的值,你可能会传入记录id和新值。

如果需要通用接口,还可以定义要传递的上下文,这样服务就可以执行任意业务逻辑。因此,您可以包括用户身份验证、用户会话状态等等……在上下文中,因为服务可能根据这些值执行额外的逻辑。

3年后,也许有点晚了,但是,也许这篇文章会帮助你。它说明了“上下文”这个词在编程中具有技术意义(而不仅仅是简单的英语含义)。

哪些编程语言是上下文无关的?

不确定你是否可以用它作为一个例子,从中提取一些信息。我也希望听到对技术编程术语“上下文”的语言不可知论的解释。

编辑:或者它至少表明了术语“上下文”可以应用于技术和编程上下文中(无意使用双关语)。这一术语的具体应用可能不止一个。

举一个实际的例子。假设你有一个特定的网页来获取/呈现基于用户(登录)和浏览器的语言的一些信息。获取信息的逻辑独立于用户和语言。您的页面将接收一个用户和一种语言…从逻辑上讲,是我还是你,是英语还是西班牙语并不重要。

一些伪代码:

class FooPage
{
    void handleRequest(RequestContext context)
    {
        User user = context.getUser();
        Locale locale = context.getLocale();

        … do some logic based on the context
    }
}

这并不难,但是理解这个概念需要一些时间

作者常常假定读者对“上下文”这个词所处的语境有详细的了解。

如何在下面的句子“the ?”运行时创建一个上下文,其中可以存储可能的注入值。这个上下文可以被修改,例如,应用程序和框架可以向上下文添加元素。

It would seem the author is using context to mean some kind of container, perhaps a heap, that holds the context of something. It has become buzz word that is taking on many meaning and confusing things. Is it the elements that are the context and are being stored in a context. To reduce the confusion of the context that the word context is being used it could be said that "the runtime creates a container to store the context in the form of elements." Better yet "the runtime creates a container to store the state in the form of elements and this container with it's state is called the CONTEXT."

Context指的是执行上下文,即从代码中给定点可到达的符号,以及这些符号在特定执行中的值。

背景是一个重要的概念,因为:

可执行单元(函数、过程、指令)在不同的上下文中可能产生不同的结果或表现不同。 上下文越大或越复杂,就越难以理解一段代码的作用(这就是避免使用全局变量的原因)。

您不必编写上下文类或传递上下文参数。传递给函数/方法的任何参数在调用时都成为执行上下文的一部分。

即使您不会说英语,我也建议您阅读Code Complete,对上下文、模块化、耦合、内聚等概念进行温和而全面的介绍。