VB.NET 'With' 声明 - 接受还是避免? [英] The VB.NET 'With' Statement - embrace or avoid?

查看:14
本文介绍了VB.NET 'With' 声明 - 接受还是避免?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在工作中,我经常参与一些项目,这些项目必须在构建期间或生命周期的早期设置某些对象的许多属性.为了方便和可读性,我经常使用 With 语句来设置这些属性.我发现

At work, I'm frequently working on projects where numerous properties of certain objects have to be set during their construction or early during their lifetime. For the sake of convenience and readability, I often use the With statement to set these properties. I find that

With Me.Elements
    .PropertyA = True
    .PropertyB = "Inactive"
    ' And so on for several more lines
End With

看起来比

Me.Elements.PropertyA = True
Me.Elements.PropertyB = "Inactive"
' And so on for several more lines

用于简单设置属性的非常长的语句.

for very long statements that simply set properties.

我注意到在调试时使用 With 存在一些问题;然而,我想知道是否有任何令人信服的理由来避免在实践中使用 With?我一直假设通过编译器为上述两种情况生成的代码基本相同,这就是为什么我总是选择编写我觉得更具可读性的内容.

I've noticed that there are some issues with using With while debugging; however, I was wondering if there were any compelling reasons to avoid using With in practice? I've always assumed the code generated via the compiler for the above two cases is basically the same which is why I've always chosen to write what I feel to be more readable.

推荐答案

如果你有很长的变量名并且最终会出现:

If you have long variablenames and would end up with:

UserHandler.GetUser.First.User.FirstName="Stefan"
UserHandler.GetUser.First.User.LastName="Karlsson"
UserHandler.GetUser.First.User.Age="39"
UserHandler.GetUser.First.User.Sex="Male"
UserHandler.GetUser.First.User.Occupation="Programmer"
UserHandler.GetUser.First.User.UserID="0"
....and so on

然后我会使用 WITH 使其更具可读性:

then I would use WITH to make it more readable:

With UserHandler.GetUser.First.User
    .FirstName="Stefan"
    .LastName="Karlsson"
    .Age="39"
    .Sex="Male"
    .Occupation="Programmer"
    .UserID="0"
end with

在后面的例子中,甚至比第一个例子有性能优势,因为在第一个例子中,我每次访问用户属性时都会获取用户,而在 WITH 的情况下,我只获取用户一次.

In the later example there are even performance benefit over the first example because in the first example Im fetching the user every time I access a user property and in the WITH-case I only fetch the user one time.

我可以在不使用 with 的情况下获得性能提升,如下所示:

I can get the performance gain without using with, like this:

dim myuser as user =UserHandler.GetUser.First.User
myuser.FirstName="Stefan"
myuser.LastName="Karlsson"
myuser.Age="39"
myuser.Sex="Male"
myuser.Occupation="Programmer"
myuser.UserID="0"

但我会选择 WITH 语句,它看起来更干净.

But I would go for the WITH statement instead, it looks cleaner.

我只是以此为例,所以不要抱怨一个有很多关键字的类,另一个例子可能是:WITH RefundDialog.RefundDatagridView.SelectedRows(0)

And I just took this as an example so dont complain over a class with many keywords, another example could be like: WITH RefundDialog.RefundDatagridView.SelectedRows(0)

这篇关于VB.NET 'With' 声明 - 接受还是避免?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆