Nullable类型之间的转换
.NET 4.0中是否有转换器支持可空类型之间的转换,以缩短如下指令:
bool? nullableBool = GetSomething(); byte? nbyte = nullableBool.HasValue ? (byte?)Convert.ToByte(nullableBool.Value) : null;
不是我知道的。
你可以写一个像这样的辅助方法:
public Nullable NullableConvert( Nullable source, Func converter) where TTarget: struct where TSource: struct { return source.HasValue ? (Nullable)converter(source.Value) : null; }
这样叫:
byte? nbyte = NullableConvert(nullableBool, Convert.ToByte);
我会写一个扩展方法:
public static class Extensions { public static TDest? ConvertTo(this TSource? source) where TDest: struct where TSource: struct { if (source == null) { return null; } return (TDest)Convert.ChangeType(source.Value, typeof(TDest)); } }
然后:
bool? nullableBool = true; byte? nbyte = nullableBool.ConvertTo();