2

我在另一个类文件中有一个函数可以获取有关电池的信息。在一个表单中,我有以下代码:

If BatteryClass.getStatus_Battery_Charging = True Then

看来 Visual Studio 接受了这一点。但是,如果我使用以下代码会更好,它也可以工作:

dim val as boolean = BatteryClass.getStatus_Battery_Charging
If val = True Then

这两种方法有区别吗?

4

2 回答 2

4

What you're asking in general is which approach is idiomatic.

The technical rule is not to invoke a method multiple times - unless you're specifically checking a volatile value for change - when its result can be preserved in a locally scoped variable. That's not what your asking but its important to understand that multiple calls should typically be bound to a variable.

That being said its better to produce less lines of code from a maintenance perspective as long as doing so improves the readability of your code. If you do have to declare a locally scoped variable to hold the return value of a method make sure to give the variable a meaningful name.

Prefer this [idiomatic VB.NET] one liner:

If BatteryClass.getStatus_Battery_Charging Then

over this:

Dim isBatteryCharging As Boolean = BatteryClass.getStatus_Battery_Charging
If isBatteryCharging Then

Another point you should concern yourself with are methods, which when invoked, create a side effect that affects the state of your program. In most circumstances it is undesirable to have a side effect causing method invoked multiple times - when possible rewrite such side affecting methods so that they do not cause any side effects. To limit the number of times a side effect will occur use the same local variable scoping rule instead of performing multiple invocations of the method.

于 2013-07-13T04:56:07.563 回答
4

没有真正的区别。

当然,如果您再次需要该值,则第二个更好。当您将值存储在变量中时,调试也稍微容易一些。

我个人倾向于使用第一个,因为我本质上是一个老派的 C 程序员!

于 2013-07-13T04:25:51.400 回答