D 2.0中有一个with
关键字,但我不确定它的用途,或者如何使用它。我对文档的搜索毫无结果。有谁知道with
关键字的用途是什么? (它是否像C#的using
语句?或者像Visual Basic的With
子句?)
答案 0 :(得分:7)
就在这里:With Statement
with语句是一种简化对同一对象的重复引用的方法。
它的用法如下:
with (expression)
{
usage();
writef("%s, %s", access, member);
}
答案 1 :(得分:6)
如果您需要,可以使用with语句构造匿名对象:
class Foo { int x; }
void main()
{
with (new Foo)
{
x = 5;
}
}
This link包含与Scintilla一起使用的with
关键字的示例代码。
答案 2 :(得分:1)
从文档中: “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 );
}