【发布时间】: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