Mar*_*son 2 .net generics nullable
我似乎已经走了一个兔子洞.我想将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);
}
}
Run Code Online (Sandbox Code Playgroud)
目标有一种使用泛型来完成所有转换的方法.这是可能的还是我必须写几个.
T : Nullable<T>作为一种约束并不真正有意义 - 想想T会发生什么; 它本身不能为空.你可以有:
where T : Nullable<U> where U : struct
Run Code Online (Sandbox Code Playgroud)
但这有点模糊.我认为制作T非可空类型更容易,只是参考Nullable<T>.我想你想要这个:
public static Nullable<T> Convert<T>(object testValue) where T : struct
{
return testValue is DBNull ? null : new Nullable<T>((T)testValue);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
748 次 |
| 最近记录: |