vb.net - 接受空值的VB.Net函数?
问题描述
我想制作一个操纵空值的子。这个想法是让它接受任何可以为空的变量,如果它有一个值,那么覆盖一个不同的值。这是我写的:
Dim a as int? = 0
Dim b as int? = 1
Sub ApplyChange(Byref Old As Nullable, ByRef Change as Nullable)
If Change.HasValue Then
Old = Change
End IF
End Sub
ApplyChange(a, b)
问题是,我收到一个错误“HasValue 不是 Nullable 的成员”并且“int?不能转换为 Nullable”。这里发生了什么?我该如何制作一个只接受可为空的子?
解决方案
不要使用Nullable
类作为参数类型。使用Nullable(Of T)
结构,这是您的变量被声明为的结构。这个:
Dim a As Integer? = 0
Dim b As Integer? = 1
是这个的简写:
Dim a As Nullable(Of Integer) = 0
Dim b As Nullable(Of Integer) = 1
这意味着您的方法可以是这样的:
Sub ApplyChange(Of T As Structure)(ByRef Old As Nullable(Of T), Change As Nullable(Of T))
If Change.HasValue Then
Old = Change
End If
End Sub
同样,ByRef
如果您没有设置参数或其任何成员,则不需要。
使用相同的速记:
Sub ApplyChange(Of T As Structure)(ByRef Old As T?, Change As T?)
If Change.HasValue Then
Old = Change
End If
End Sub
推荐阅读
- javascript - 聚合物 3 中未定义的工厂全局变量
- javascript - Javascript 模块包含在量角器配置 js 文件中
- javascript - 传单层上的多个即时过滤
- c# - 从 xaml 代码创建对象并识别它们
- javascript - 从数组中删除特定元素
- angular - 获取加载指示器的 http post 请求进度
- r - 仅当数字大于阈值时如何绘制 ggplots 六边形
- python-3.x - 我正在尝试使这个简单的套接字“ddos”多线程,但它没有任何回报
- php - 我如何将 spatie/laravel-backup 与 Postgres DB 集成?
- angular - 为什么值格式化程序被应用于单元格但显示的值不会改变 ag-grid