我真的很喜欢VB的一个特性...... With声明.C#有任何等价物吗?我知道你可以使用using不必键入命名空间,但它仅限于此.在VB中你可以这样做:
With Stuff.Elements.Foo
.Name = "Bob Dylan"
.Age = 68
.Location = "On Tour"
.IsCool = True
End With
Run Code Online (Sandbox Code Playgroud)
C#中的相同代码是:
Stuff.Elements.Foo.Name = "Bob Dylan";
Stuff.Elements.Foo.Age = 68;
Stuff.Elements.Foo.Location = "On Tour";
Stuff.Elements.Foo.IsCool = true;
Run Code Online (Sandbox Code Playgroud)
Rob*_*vey 44
不是,你必须分配一个变量.所以
var bar = Stuff.Elements.Foo;
bar.Name = "Bob Dylan";
bar.Age = 68;
bar.Location = "On Tour";
bar.IsCool = True;
Run Code Online (Sandbox Code Playgroud)
或者在C#3.0中:
var bar = Stuff.Elements.Foo
{
Name = "Bob Dylan",
Age = 68,
Location = "On Tour",
IsCool = True
};
Run Code Online (Sandbox Code Playgroud)
除了对象初始化器(仅在构造函数调用中可用)之外,您可以获得的最佳结果是:
var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...
Run Code Online (Sandbox Code Playgroud)
C#3.0中最接近的是,您可以使用构造函数初始化属性:
Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
94593 次 |
| 最近记录: |