Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recast objects from a Dictionary(Of String, Object) in VB.Net

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
like image 573
Alexander Van Atta Avatar asked Nov 30 '25 12:11

Alexander Van Atta


1 Answers

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.

like image 174
Esoteric Screen Name Avatar answered Dec 03 '25 05:12

Esoteric Screen Name



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!