背景是我希望能够初始化 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/