我真的很喜欢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) 我今天看了Infragistics控件库的在线帮助,看到了一些使用With关键字在选项卡控件上设置多个属性的VB代码.我做了任何VB编程已有将近10年了,我几乎忘记了这个关键字甚至存在.由于我还是比较新的C#,我很快就去看它是否有类似的构造.可悲的是,我找不到任何东西.
C#是否有一个关键字或类似的构造来模仿VB中With关键字提供的功能?如果没有,是否有技术原因导致C#没有这个?
编辑: 我在询问我的问题之前搜索了一个现有的条目,但没有找到Ray提到的那里(这里).那么,为了改进这个问题,有没有技术上的原因为什么C#没有这个?Gulzar将其钉住了 - 不,没有技术上的理由说明为什么C#没有With关键字.这是语言设计师的设计决定.
我知道C#有using关键字,但会using自动处理对象.
With...End With在Visual Basic 6.0中是否存在等价?
在Visual Basic中,如果要更改单个对象的多个属性,则需要With/End With声明:
Dim myObject as Object
// ' Rather than writing:
myObject.property1 = something
myObject.property2 = something2
// ' You can write:
with myObject
.property1 = something
.property2 = something2
...
End With
Run Code Online (Sandbox Code Playgroud)
我知道C#可以在创建新对象时执行此操作:
Object myObject = new Object { property1 = something, property2 = something2, ...};
Run Code Online (Sandbox Code Playgroud)
但是,如果myOject已经创建(如Visual Basic正在做什么),我该怎么做?
使用 Kotlin 时,可以使用apply设置现有对象的多个属性并保持代码更清晰,例如,而不是:
person.firstName = "John"
person.lastName = "Doe"
person.phone = "123 456 789"
Run Code Online (Sandbox Code Playgroud)
我们可以用:
person.apply {
firstName = "John"
lastName = "Doe"
phone = "123 456 789"
}
Run Code Online (Sandbox Code Playgroud)
是否有与applyC# 中的等效项?
最接近的是,using但据我所知,它不能以这种方式使用。
编辑:我知道C# 中的对象初始值设定项,但实际上我正在寻找可以为现有对象(例如从数据库中获取的对象)完成的操作。
考虑以下情况
public class SomethingWithAReallyReallyAnnoyinglyLongName{
public struct Names
{
public const string SomeConstant = "Hello";
public const string SomeOtherConstant = "World";
}
}
Run Code Online (Sandbox Code Playgroud)
当在上下文之外时,是否有一种引用方式SomethingWithAReallyReallyAnnoyinglyLongName.Names.SomeConstant而不必引用?SomethingWithAReallyReallyAnnoyinglyLongNameSomethingWithAReallyReallyAnnoyinglyLongName
// Won't work "Struct Name is not valid at this point."
var names = SomethingWithAReallyReallyAnnoyinglyLongName.Names;
SomeFunction(names.SomeConstant, names.SomeOtherConstant);
// Won't work "Cannot access static constant..."
var names = new SomethingWithAReallyReallyAnnoyinglyLongName.Names();
SomeFunction(names.SomeConstant, names.SomeOtherConstant);
Run Code Online (Sandbox Code Playgroud)
长类名是自动生成的,所以我不能改变它,但我可能会改变关于Names结构的任何内容(使它成为一个类,将consts更改为const不是等等).
有任何想法吗?