Conversion between Nullable types

后端 未结 2 1102
逝去的感伤
逝去的感伤 2021-01-12 11:20

Is there a converter in .NET 4.0 that supports conversions between nullable types to shorten instructions like:

bool? nullableBool = GetSomething();
byte? nb         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 11:39

    Not that I am aware of.
    You could just write a helper method like this:

    public Nullable NullableConvert(
              Nullable source, Func converter)
        where TTarget: struct
        where TSource: struct
    {
        return source.HasValue ? 
                   (Nullable)converter(source.Value) : 
                   null;
    }
    

    Call it like this:

    byte? nbyte = NullableConvert(nullableBool, Convert.ToByte);
    

提交回复
热议问题