Len() 函数 vs String.Length 属性;选择哪个? [英] Len() function vs String.Length property; which to choose?

查看:28
本文介绍了Len() 函数 vs String.Length 属性;选择哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 VB6 过渡到 VB.Net (VS 2010),并且对后者有一个基本的而不是广泛的了解.我显然有相当多的代码......我犹豫是否使用升级"这个词,因为端口"会更合适,因为过去版本的 VS 中的升级向导也可能刚刚注释掉了代码并说喂,你为什么不从头开始?"

I'm making the transition from VB6 to VB.Net (VS 2010) and have a basic rather than expansive understanding of the latter. I obviously have quite a bit of code to... I hesitate to use the word "upgrade" when "port" would be more apt given that the upgrade wizard in past versions of VS may as well have just commented out the code and said "Hey, why don't you re-start from scratch?"

在我介绍的一个过程中,Len() 函数用于确定字符串变量的长度.这在 VB.Net 中仍然有效(尽管我认为它实际上是对 Strings.Len 方法的调用),但另一种方法是查询 .Length 属性变量.

In one procedure which I'm bringing across the Len() function was used to determine the length of a string variable. That still works in VB.Net (though I imagine that it's actually a call to the Strings.Len Method), but the other alternative is to just query the .Length property of the variable.

问题是使用哪个以及为什么使用.我浏览了相关的 MSDN 页面,他们似乎告诉我的只是该方法/属性存在.没有提及性能问题,尤其是在可能涉及大量调用的循环时.

The question is which to use and why. I've looked through the relevant MSDN pages and all they seem to tell me is that the method/property exists. Nothing is said about performance issues, particularly when loops of large numbers of calls might be involved.

我的问题是,是否有人知道使用一种方法比另一种方法有任何经过测试和确认的好处,或者这仅仅是个人偏好的问题.任何关于我在推进过程中可能遇到的类似情况的指示也将不胜感激,尽管鉴于 Stack Overflow 指南,这只是我有兴趣查看是否有特定答案的一个问题.

My question, then, is whether anyone is aware of any tested and confirmed benefit of using one approach over the other, or whether it's merely a question of personal preference. Any pointers on similar situations that I might encounter as I make the progression would also be appreciated though given the Stack Overflow guidelines it's just this one issue that I'm interested in seeing whether there's a specific answer to.

推荐答案

因为您使用的是 VB.NET,所以您的 Strings 可以是 Nothing 并且除非您明确检查为此,大多数 VB 方法,包括 Len,会将其视为与 String.Empty 相同,即 "".

Because you're using VB.NET, your Strings can be Nothing and unless you explicitly check for that, most VB methods, including Len, will treat it the same as String.Empty i.e. "".

使用 Reflector,您可以看到 Len 被实现为空检查,对于 Nothing 返回 0,否则返回 .Length,并且 JITter 可能会内联调用.

With Reflector you can see Len is implemented as a null check, returning 0 for Nothing and otherwise returning .Length, and the JITter will likely in-line the call.

因此,如果您使用其他 VB 方法,我建议您也使用 Len,除非您知道 String 不是 Nothing> 或到处检查Nothing.

So, if you're using other VB methods, I'd suggest using Len too, unless you know the String is not Nothing or check for Nothing everywhere.

这篇关于Len() 函数 vs String.Length 属性;选择哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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