【问题标题】:VB.NET GenericsVB.NET 泛型
【发布时间】:2012-05-02 05:33:03
【问题描述】:

我有一个功能如下:

Function foo(ByVal c As CustomType, ByValue str as String) As Object
   Dim o as Object
   Select Case c.TypeName
     Case "System.String"
       If str = String.Empty Then
         o = DBNull.Value
       Else
         o = value
       End If
     Case "System.Int64"
       Try
         o = Long.Parse(value, Globalization.NumberStyles.Any)
       Catch
         o = DBNull.Value
       End Try
     Case "System.Double"
       Try
         o = Double.Parse(value, Globalization.NumberStyles.Any)
       Catch
         o = DBNull.Value
       End Try
     Case "System.Int32"
       Try
         o = Int32.Parse(value, Globalization.NumberStyles.Any)
       Catch
         o = DBNull.Value
       End Try
     Case "System.DateTime"
       Try
         o = DateTime.Parse(value)
       Catch
         o = DBNull.Value
       End Try
   Return o
End Function

这个函数让我想写一个通用版本。由于像 C++ 这样的 .NET 中不允许部分专业化(如果我在这里错了,请纠正我),我可以通过哪些方式使用泛型的任何特性。我做了一个尴尬的尝试,但失败了:

Function foo(Of T)(...) as Object
  Dim o As Object
  Try
     o = T.Parse(...) 'This doesnt work
  Catch
     o = DBNull.Value  
  End Try  
  ...
End Function
'Add functions for handling String and DateTime maybe?

【问题讨论】:

  • 为什么无效的字符串会导致DBNull?这听起来像是一个糟糕的设计选择,IMO。事实上,除非这与(比如说)sql 参数打包直接相关,否则我不知道为什么要涉及DBNull根本
  • 这确实和SQL参数打包有关。

标签: .net vb.net generics


【解决方案1】:

确实,您不能将T.whatever 与泛型一起使用;只能使用Tinstance 方法(基于T 的已知约束)。

可能是这样的:

// return object since SQL parameter packing
static object Parse<T>(string value)
{
    if (string.IsNullOrEmpty(value)) return DBNull.Value; // for SQL parameter
    return TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}

?

【讨论】:

    【解决方案2】:

    您可以使用反射以某种方式简化您的代码:

    If c.Type.Primitive Then
       o = c.Type.GetMethod("Parse").Invoke(Nothing, New Object() {value, Globalization.NumberStyles.Any}) 
    

    【讨论】:

      猜你喜欢
      • 2011-02-26
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多