我非常喜欢VB的一个特性...... With
语句。 C#有任何等价物吗?我知道你可以使用using
来输入命名空间,但仅限于此。在VB中你可以这样做:
With Stuff.Elements.Foo
.Name = "Bob Dylan"
.Age = 68
.Location = "On Tour"
.IsCool = True
End With
C#中的相同代码是:
Stuff.Elements.Foo.Name = "Bob Dylan";
Stuff.Elements.Foo.Age = 68;
Stuff.Elements.Foo.Location = "On Tour";
Stuff.Elements.Foo.IsCool = true;
答案 0 :(得分:41)
不是,你必须分配一个变量。所以
var bar = Stuff.Elements.Foo;
bar.Name = "Bob Dylan";
bar.Age = 68;
bar.Location = "On Tour";
bar.IsCool = True;
或者在C#3.0中:
var bar = Stuff.Elements.Foo
{
Name = "Bob Dylan",
Age = 68,
Location = "On Tour",
IsCool = True
};
答案 1 :(得分:8)
除了对象初始值设定项(仅在构造函数调用中可用)之外,最好的是:
var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...
答案 2 :(得分:5)
C#3.0中最接近的一点是,您可以使用构造函数初始化属性:
Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}