.NET 4.0中是否有转换器支持可空类型之间的转换以缩短指令,例如:
bool? nullableBool = GetSomething();
byte? nbyte = nullableBool.HasValue ? (byte?)Convert.ToByte(nullableBool.Value) : null;
Run Code Online (Sandbox Code Playgroud)
我会写一个扩展方法:
public static class Extensions
{
public static TDest? ConvertTo<TSource, TDest>(this TSource? source)
where TDest: struct
where TSource: struct
{
if (source == null)
{
return null;
}
return (TDest)Convert.ChangeType(source.Value, typeof(TDest));
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
bool? nullableBool = true;
byte? nbyte = nullableBool.ConvertTo<bool, byte>();
Run Code Online (Sandbox Code Playgroud)
据我所知,情况并非如此。
您可以编写一个像这样的辅助方法:
public Nullable<TTarget> NullableConvert<TSource, TTarget>(
Nullable<TSource> source, Func<TSource, TTarget> converter)
where TTarget: struct
where TSource: struct
{
return source.HasValue ?
(Nullable<TTarget>)converter(source.Value) :
null;
}
Run Code Online (Sandbox Code Playgroud)
像这样称呼它:
byte? nbyte = NullableConvert(nullableBool, Convert.ToByte);
Run Code Online (Sandbox Code Playgroud)