【问题标题】:Conversion between Nullable typesNullable 类型之间的转换
【发布时间】:2011-03-30 23:50:17
【问题描述】:

.NET 4.0 中是否有转换器支持可空类型之间的转换以缩短指令,例如:

bool? nullableBool = GetSomething();
byte? nbyte = nullableBool.HasValue ? (byte?)Convert.ToByte(nullableBool.Value) : null;

【问题讨论】:

  • 这是最整洁的方式。如果需要,您可以将其封装在您自己的实用程序方法中。

标签: c# .net nullable


【解决方案1】:

我会写一个扩展方法:

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

【讨论】:

  • 最好的答案。
【解决方案2】:

我不知道。
你可以像这样写一个辅助方法:

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

这样称呼它:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 2017-11-05
    • 2011-08-18
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    相关资源
    最近更新 更多