I have a program that runs a bunch of different types of tests. The each test has a bunch of different settings that can be set. I am trying to export the settings that were used for each test to an excel file. Write now I have all the settings stored in a Dictionary(Of String, Object) because the value of the settings can be different types i.e (Double, Integer, String, Boolean). I am trying to recast the values from the dictionary like so but the DirectCast does not like the t, It says type t is not defined. I also tried CType but it does not seem to work. settings is of type Dictionary(Of String, Object)

Private Sub writeTestSettings(ByRef book As HSSFWorkbook, ByVal settings As Dictionary(Of String, Object))
    Dim settingsSheet As HSSFSheet = book.CreateSheet("Test Configuration")

    Dim i As Integer = 0
    For Each key In settings.Keys
        Dim row = settingsSheet.CreateRow(i)
        Dim cell1 As HSSFCell = row.CreateCell(0)
        cell1.SetCellValue(key)
        Dim cell2 As HSSFCell = row.CreateCell(1)
        Dim value As Object = settings(key)
        Dim t As Type = value.GetType()
        cell2.SetCellValue(DirectCast(value, t))

    Next
End Sub
有帮助吗?

解决方案

If you're on .NET 4.0 or later, you can use CTypeDynamic instead. See also this question.

    Dim t As Type = value.GetType()
    cell2.SetCellValue(CTypeDynamic(value, t))

You might also want to consider changing your settings' storage mechanism a bit. Putting several different types in a Dictionary of Objects may make future maintenance and debugging obnoxious. As an off the cuff idea, one possibility would be a simple wrapper class with private type-specific dictionaries and overloaded accessors and mutators.

其他提示

You can't cast directly because you don't know the type at compile time. It's not very clean code but you could do it with a Select Case:

Select Case t
    Case GetType(Double)
        Dim doubleValue = CType(value, Double)
        cell2.SetCellValue(doubleValue)
    Case GetType(Integer)
        Dim integerValue = CType(value, Integer)
        cell2.SetCellValue(integerValue)
    ...
End Select
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top