.NET 4.0 中是否有一个转换器支持可空类型之间的转换以缩短指令,例如:
bool? nullableBool = GetSomething();
byte? nbyte = nullableBool.HasValue ? (byte?)Convert.ToByte(nullableBool.Value) : null;
我会写一个扩展方法:
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));
}
}
进而:
bool? nullableBool = true;
byte? nbyte = nullableBool.ConvertTo<bool, byte>();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)