不可变的点网字符串
我通常将 vb.net 中的字符串变量定义为
Dim f_sName as string=String.Empty
f_sName = "foo"
鉴于 .net 中字符串的不可变性质,是否有更好的方法来初始化字符串并处理“变量 'f_sName ' 在被赋值之前使用。一个 null运行时可能会导致引用异常。”警告?
另外,对于没有不接受任何参数的构造函数的类(例如 System.Net.Sockets.NetworkStream),定义和初始化该类型变量的最佳方法是什么?
I usually define my string variables in vb.net as
Dim f_sName as string=String.Empty
f_sName = "foo"
Given the immutable nature of strings in .net, is there a better way to initialize strings and deal with the "Variable 'f_sName ' is used before it has been assigned a value. A null reference exception could result at runtime." warning?
Also for classes that do not have constructors which accept no arguments such as System.Net.Sockets.NetworkStream, what is the best way to define and initialize a variable of that type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这与字符串不可变无关。
一个
更好的优选模式是但这取决于具体情况是否可以使用。
与 Nothing 或 Empty 初始化相同。如果您想尽早捕获错误,那么:
对于像 NetworkStream 这样的类,同样的事情:不要创建实例,也不要声明变量,直到需要它们为止。对于像 NetworkStream 这样的 Disposable 类,这意味着使用 using 子句:
在这个狭窄的范围之外提供“fs”既不理想也没有用。
This has nothing to do with the strings being immutable.
A
betterpreferable pattern would beBut it depends on the situation if you can use that.
Same for initializing with Nothing or Empty. If you want to catch errors early, then:
And concerning classes like NetworkStream, same thing: don't create instance and don't declare variables until you need them. For a Disposable class like NetworkStream this means use a Using clause:
It is neither desirable nor useful to have 'fs' available outside that narrow scope.
或者
顺便说一句:将
mixedCase
变量命名与下划线
混合使用(如 f_sName 中)大多数时候看起来很奇怪,这个变量名代表什么?or
By the way: mixing
mixedCase
variable naming withunderscores
(as in f_sName) looks strange most of the time, what does this variable name stand for?将字符串初始化为 null 和 String.Empty 几乎是同一件事。就我个人而言,我认为将其设置为 string.empty 确实是处理它的最佳方法。将其设置为 null 将导致抛出 null 引用异常,但将其设置为 String.Empty 则不会。
人们可以争论两种方式之一初始化它的优点,但优化方面没有明显的区别。
Initializing a string to null and to String.Empty are pretty much the same thing. Personally, I think setting it to string.empty really is the best way of handling it. Setting it to null will result in throwing null reference exceptions though where as setting it to String.Empty will not.
One can argue the merits of initializing it one of two ways, but optimization wise there is no discernible difference.