简体   繁体   English

如何从VB.Net中的Dictionary(Of String,Object)重铸对象

[英]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. 我正在尝试将用于每个测试的设置导出到excel文件。 Write now I have all the settings stored in a Dictionary(Of String, Object) because the value of the settings can be different types ie (Double, Integer, String, Boolean). 现在写我将所有设置存储在Dictionary(Of String,Object)中,因为设置的值可以是不同的类型,即(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. 我试图像这样重写字典中的值,但DirectCast不喜欢t,它说类型t没有定义。 I also tried CType but it does not seem to work. 我也试过CType,但似乎没有用。 settings is of type Dictionary(Of String, Object) 设置类型为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. 如果您使用的是.NET 4.0或更高版本,则可以使用CTypeDynamic 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执行此操作:

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM