Conversion between Nullable types

后端 未结 2 1099
逝去的感伤
逝去的感伤 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:48

    I would write an extension method:

    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));
        }
    }
    

    and then:

    bool? nullableBool = true;
    byte? nbyte = nullableBool.ConvertTo();
    

提交回复
热议问题