【发布时间】:2011-02-21 23:03:26
【问题描述】:
D 2.0 中有一个with 关键字,但我不确定它的作用或如何使用它。我对文档的搜索没有结果。有谁知道with 关键字的用途是什么? (是不是像 C# 的 using 语句?还是像 Visual Basic 的 With 子句?)
【问题讨论】:
标签: d
D 2.0 中有一个with 关键字,但我不确定它的作用或如何使用它。我对文档的搜索没有结果。有谁知道with 关键字的用途是什么? (是不是像 C# 的 using 语句?还是像 Visual Basic 的 With 子句?)
【问题讨论】:
标签: d
就在这里:With Statement
with 语句是一种简化对同一对象的重复引用的方法。
它是这样使用的:
with (expression)
{
usage();
writef("%s, %s", access, member);
}
【讨论】:
with 语句类似于VB 的with 子句。
如果需要,可以使用 with 语句构造匿名对象:
class Foo { int x; }
void main()
{
with (new Foo)
{
x = 5;
}
}
This link 有一些与 Scintilla 一起使用的 with 关键字的示例代码。
【讨论】:
来自文档: "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 );
}
【讨论】: