Conversion between Nullable types

扶醉桌前 提交于 2019-12-19 06:21:16

问题


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;

回答1:


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



回答2:


I would write an extension method:

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

and then:

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


来源:https://stackoverflow.com/questions/5487685/conversion-between-nullable-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!