有一个转换器在.NET 4.0中支持可空类型之间的转换,缩短像说明:
布尔? nullableBool = GetSomething();
字节? nbyte = nullableBool.HasValue? (字节?)Convert.ToByte(nullableBool.Value):空;
解决方案
这并不是说我知道。 你可以只写一个辅助方法是这样的:
市民可空< TTarget> NullableConvert< TSource,TTarget>(
可空< TSource>源,Func键和LT; TSource,TTarget>转换器)
其中,TTarget:结构
其中,TSource:结构
{
返回source.HasValue?
(可空< TTarget>)转换器(source.Value):
空值;
}
这样称呼它:
字节? nbyte = NullableConvert(nullableBool,Convert.ToByte);
Is there a converter in .NET 4.0 that supports conversions between nullable types to shorten instructions like:
bool? nullableBool = GetSomething();
byte? nbyte = nullableBool.HasValue ? (byte?)Convert.ToByte(nullableBool.Value) : null;
解决方案
Not that I am aware of. You could just write a helper method like this:
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;
}
Call it like this:
byte? nbyte = NullableConvert(nullableBool, Convert.ToByte);