日期:2010-06-03 浏览次数:20486 次
Public Function GenericCast(Of U, V)(ByVal obj As U) As V
Return CType(obj, V)
End Function
Return DirectCast(DirectCast(obj, Object), V)
return (V)(object)obj;
Public Function GenericCast(Of U, V)(ByVal obj As U) As V
Return CType(DirectCast(obj, Object), V)
End Function
static V GenericCast<U, V>(U obj)
{
IConvertible convertibleObj = obj as IConvertible;
if (convertibleObj != null)
{
Type t = typeof(V);
switch (Type.GetTypeCode(t))
{
case TypeCode.Boolean:
return (V)(object)convertibleObj.ToBoolean(null);
case TypeCode.Byte:
return (V)(object)convertibleObj.ToByte(null);
case TypeCode.Char:
return (V)(object)convertibleObj.ToChar(null);
//.........
default:
//None of them, use the following default way..
break;
}
}
return (V)(object)obj;
}
static V GenericCast<U, V>(U obj)
{
return (V)Convert.ChangeType(obj, typeof(V));
}
Public Function GenericCast(Of U, V)(ByVal obj As U) As V
Try
Return CType(DirectCast(obj, Object), V)
Catch ex As InvalidCastException Return DirectCast( _
CompilerServices.Conversions.ChangeType(obj, GetType(V)), V)
End Try
End Function