【问题标题】:What does the "with" keyword do in D 2.0?D 2.0 中的“with”关键字有什么作用?
【发布时间】:2011-02-21 23:03:26
【问题描述】:

D 2.0 中有一个with 关键字,但我不确定它的作用或如何使用它。我对文档的搜索没有结果。有谁知道with 关键字的用途是什么? (是不是像 C# 的 using 语句?还是像 Visual Basic 的 With 子句?)

【问题讨论】:

    标签: d


    【解决方案1】:

    就在这里:With Statement

    with 语句是一种简化对同一对象的重复引用的方法。

    它是这样使用的:

    with (expression)
    {
      usage();
      writef("%s, %s", access, member);
    }
    

    【讨论】:

    • o__o 这是一个声明?我在“表达式”部分中查找并找不到它……而且从搜索框中搜索显然并不容易。谢谢!! :)
    • 您的回答会提供更多信息,它还回答了问题,而不仅仅是链接到答案。 D 的with 语句类似于VB 的with 子句。
    【解决方案2】:

    如果需要,可以使用 with 语句构造匿名对象:

    class Foo { int x; }
    void main()
    {
        with (new Foo)
        {
            x = 5;
        }
    }
    

    This link 有一些与 Scintilla 一起使用的 with 关键字的示例代码。

    【讨论】:

      【解决方案3】:

      来自文档: "with 语句是一种简化对同一对象的重复引用的方法。"

      当我在文档中看到它时,我的想法是,它对语法需要看起来很熟悉并且代码重复访问同一个对象的数学很有帮助。

      struct Values
      {
          double x,y,vx,vy,ax,ay,dt;
      
          int i;
          void set_i( int i )
          {
              this.i = i;
          }
      
          alias int NestedType;
      };
      
      
      
      void main()
      {
          //Setup:
          Values vals;
          vals.i = 10;
      
          //Usage of with:
          with(vals)
          // with(otherVals)    // <<--  Easy to switch the 'with' scope to deal with a different instance:
          {
              // Imports all the member symbols of the struct or class into present scope
              // without needing to refer every time to vals:
              assert( i == 10 );
      
              // Good for "repeated references to the same object":   Helpful for maths where the syntax needs to look familiar, and repeatedly accesses the same object:
              x  += vx*dt;
              y  += vy*dt;
              vx += ax*dt;
              vy += ay*dt;
      
              // Call the member functions too:
              set_i(42);
      
              // ... and get nested types/enums etc etc
              NestedType ex;
          }
          // Results are persist (i.e.:  all above writes were by reference:
          assert( vals.i == 42 );
      
      
          //Equivalent usage without 'with':
          {
              Values* vp = &vals;      // get a reference to vals
      
              assert( vp.i == 42 );
      
              // This looks a lot Uglier than the previous one:
              vp.x  += vp.vx*vp.dt;
              vp.y  += vp.vy*vp.dt;
              vp.vx += vp.ax*vp.dt;
              vp.vy += vp.ay*vp.dt;
      
              vp.set_i(56);
              Values.NestedType ex;
          }
      
          assert( vals.i == 56 );
      
      }
      

      【讨论】:

        猜你喜欢
        • 2017-11-21
        • 1970-01-01
        • 2014-07-19
        • 2010-10-07
        • 2019-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-12
        相关资源
        最近更新 更多