【问题标题】:How to store System.Type w/o late binding problem?如何存储 System.Type 没有后期绑定问题?
【发布时间】:2011-06-25 03:34:53
【问题描述】:

我正在尝试将 DbDataReader.GetSchemaTable.DataRow 的“DataType”字段值(System.Type 类型)存储到 System.Type 类型的类字段中。

即:

Class MyClass

  Private _ColumnName As String
  Private _DataType As Type

  Sub New(row As DataRow)
    _ColumnName = Convert.ToString(row("ColumnName"))
    _DataType = row("DataType")
  End Sub

End Class

我可以通过转换为字符串来解决 ColumnName 的后期绑定问题,但我不知道如何处理 DataType。

如果我使用_DataType = row("DataType").GetType,则存储 System.RuntimeType 而不是实际类型。

【问题讨论】:

    标签: .net vb.net


    【解决方案1】:

    如果您知道它是 Type 的实例,则使用 DirectCast(row("DataType"), Type)

    Class MyClass
    
      Private _ColumnName As String
      Private _DataType As Type
    
      Sub New(row As DataRow)
        _ColumnName = Convert.ToString(row("ColumnName"))
        _DataType = DirectCast(row("DataType"), Type)
      End Sub
    
    End Class
    

    【讨论】:

    • 这似乎比 CType 快,所以你得到了点头。
    【解决方案2】:

    我相信您会想使用Type.GetType(row("DataType")),假设row("DataType") 是字符串的完整类型名称。

    【讨论】:

    • 不是字符串,是 System.Type。
    • @ic3b3rg - 那么你只需要像这样投射它:(Type)(row("DataType"))
    • @ic3b3rg - 抱歉,VB 版本是CType(row("DataType"), Type)
    【解决方案3】:

    这在数据集中非常相似,

    oDataSet.Tables(0).Rows.GetType().ToString
    

    你可以试试这个

      _DataType = row(0).GetType.ToString()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多