构造函数链接和空引用测试
如何在调用其他构造函数之前测试空值?
说:
' class MyHoyr '
Public Sub New(ByVal myHour As MyHour)
' Can't doing it here !!!! '
If myHour Is Nothing Then Throw New ArgumentNullException("myHour")
' Constructor call should be first '
Me.New(myHour._timeSpan)
' Here is too late... '
End Sub
Private Sub New(ByVal timeSpan As TimeSpan)
'.... '
End Sub
How to test the null value BEFORE calling the other constructor?
Say:
' class MyHoyr '
Public Sub New(ByVal myHour As MyHour)
' Can't doing it here !!!! '
If myHour Is Nothing Then Throw New ArgumentNullException("myHour")
' Constructor call should be first '
Me.New(myHour._timeSpan)
' Here is too late... '
End Sub
Private Sub New(ByVal timeSpan As TimeSpan)
'.... '
End Sub
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我在 C# 中执行此操作的方法是在管道中使用静态方法,例如:
我假设您可以在 VB 中执行非常类似的操作。 (共享方法?)
Reflector 向我保证这会转化为:
The way I do that in C# is by using a static method in the pipe, for example:
I assume you can do something very similar in VB. (shared methods?)
Reflector assures me this translates into:
一个丑陋的解决方法是扩展方法:
使用如下:
An ugly workaround would be an extension method:
Used like:
处理这个问题的一个简单方法是使用“命名构造函数”的思想,也称为工厂方法。
您可以使用 System.Drawing.Color.FromArgb 查看类似的示例 使用工厂方法来避免歧义。
A simple way to handle this is to use the idea of "named constructors", aka factory methods.
You can see similar examples with System.Drawing.Color.FromArgb which use factory methods to avoid ambiguity.
我最初的冲动是建议您甚至没有采用 MyHour 实例的构造函数。相反,让用户检查类之外的任何内容:
但是,使用私有构造函数实际构造对象,如下所示,可能会起作用(未经测试):
My original impulse was to suggest that you not even have the constructor that takes the MyHour instance. Instead, make the user check for Nothing outside of the class:
However, using a private constructor to actually construct the object, like this, might work (not tested):