vb.net - 对于每个范围内不可用的每个变量

标签 vb.net foreach

背景是我希望能够初始化 DataTable 上的空白行,而不必总是检查 DBNull.Value 。我有一个扩展方法,它创建一个新的空白行,然后使用该列的默认类型填充该行中的每个值。

<Extension()> _
Public Function NewBlankRow(ByVal table As DataTable) As DataRow
    Dim row As DataRow = table.NewRow()
    For Each col As DataColumn In table.Columns
        row(col.ColumnName) = CType(Nothing, col.DataType)
    Next
    Return row
End Function

我在第二次使用 col 时收到以下消息(CType 中的那个)

Cannot resolve symbol 'col'

对于 C-Sharper,请调用 CType(Nothing, T)应该与调用 Default<T> 相同

有更好的方法吗?为什么我无法访问CType内的col ?

最佳答案

CType不是运行时函数。现在是编译时间。第二个参数中的数据类型必须在编译时指定。

http://msdn.microsoft.com/en-us/library/4x2877xb%28v=vs.80%29.aspx

CType is compiled inline, which means that the conversion code is part of the code that evaluates the expression. In some cases there is no call to a procedure to accomplish the conversion, which makes execution faster.

它与 Default<T> 不一样在这种情况下,因为 NewBlankRow不是通用方法。无论如何,Default<T>也是编译时,并且在 T 时不可用被指定为运行时表达式。

创建 col.DataType 的默认实例您可以使用反射,例如 Activator.CreateInsatnce(col.DataType) .

关于vb.net - 对于每个范围内不可用的每个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17088644/

相关文章:

.net - VB6 格式函数 : analog in . NET

Vb.Net - 计算数据读取器返回的列数

c# - 迭代变量如何只读?

c# - 无法让 .Dispose() 在 foreach 循环中工作

php - 使用数组搜索数据库,然后使用 PHP 在 foreach 循环中回显/打印结果

mysql - 将图像保存到 mysql 数据库时出现问题。程序运行完美,没有错误

javascript - 我们如何实现 CssClass active on link Button Click

mysql - 通过VB.NET向mySQL传输数据

Java:for/forEach遍历int矩阵

PHP 退出内部 foreach 循环并继续执行外部循环