2

我好像掉进了兔子洞。我想将 ADO .NET 数据集中的数据转换为 Nullable 类型。起初我认为直接演员(int?)会做到这一点。我是多么天真。错了,大错特错。现在我正在尝试编写一个通用转换器,但我对语法感到困惑。这就是 2005 年 - 一定有人已经解决了这个问题。你?

问题是,当我尝试在转换器上使用 Nullable 类型作为约束时,出现语法错误:

public class NullableDBConversion
{
  public static T Convert<T>(object testValue) where T : Nullable<T>
  {
    if (testValue is DBNull)
    {
      return new Nullable<T>();
    }

    return new Nullable<T>((T)testValue);
  }
}

目标有一个使用泛型进行所有转换的方法。这是可能的还是我必须写几个。

4

1 回答 1

7

T : Nullable<T>作为约束并没有真正意义 - 想想T必须是什么;它本身不能为空。你可以有:

where T : Nullable<U> where U : struct

但这有点晦涩难懂。我认为制作T不可为空的类型并仅引用Nullable<T>. 我想你想要这个:

public static Nullable<T> Convert<T>(object testValue) where T : struct
{
    return testValue is DBNull ? null : new Nullable<T>((T)testValue);
}
于 2009-05-15T21:03:04.877 回答