【问题标题】:Parsing/Converting string into Generic nullable type falling back to UnderlyingType default将字符串解析/转换为通用可空类型,回退到 UnderlyingType 默认值
【发布时间】:2014-02-28 00:16:20
【问题描述】:

在以下场景中寻找“单线”以使用 GetValueOrDefault()。这是一个 LINQPad 脚本,您应该可以直接加入。

void Main()
{
    Foo<string>( null ).Dump();
    Foo<string>( "Hello" ).Dump();
    Foo<double?>( "" ).Dump();
    Foo<double?>( "10" ).Dump();
    Foo<DateTime?>( "" ).Dump();
    Foo<DateTime?>( "2014-01-01" ).Dump();  
}

// Define other methods and classes here
public T Foo<T>( string value )
{
    var changeType = typeof( T );
    var convertType = IsNullable( changeType )
        ? new System.ComponentModel.NullableConverter( typeof( T ) ).UnderlyingType
        : changeType;

    if ( string.IsNullOrEmpty( value ) && IsNullable( changeType ) )
    {
        // Wanted to do this...couldn't figure out how to get 0 or min date for double?/datetime?
        // return default( T ).GetValueOrDefault(); would be obvious choice, but compiler doesn't know
        // T is nullable so the GetValueOrDefault() extension isn't available.
        if ( changeType == typeof( DateTime? ) )
        {
            return (T)(object)DateTime.MinValue;
        }
        else 
        {
            return (T)(object)0d;
        }
    }
    else
    {
        return (T)Convert.ChangeType( value, convertType );
    }
}
private bool IsNullable( Type type )
{
  return ( type != null && type.IsGenericType && type.GetGenericTypeDefinition().Equals( typeof( Nullable<> ) ) );
}

【问题讨论】:

    标签: c# .net generics type-conversion nullable


    【解决方案1】:

    以下对我有用,请注意Activator.CreateInstance

    public T Foo<T>(string value) 
    {
        var changeType = typeof(T);
        var convertType = IsNullable(changeType)
            ? new System.ComponentModel.NullableConverter(typeof(T)).UnderlyingType
            : changeType;
    
        if (string.IsNullOrEmpty(value) && IsNullable(changeType))
        {
            var defValue = Activator.CreateInstance(
                Nullable.GetUnderlyingType(changeType));
            return (T)defValue;
        }
        else
        {
            return (T)Convert.ChangeType(value, convertType);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 2023-04-09
      • 1970-01-01
      • 2011-01-01
      • 2020-10-30
      • 2010-10-20
      相关资源
      最近更新 更多