Tôi có đoạn code dưới đây và tôi cần phải chuyển đổi một chuỗi để một kiểu mà cũng được quy định từ String:Làm thế nào để chuyển đổi một chuỗi thành một kiểu dữ liệu khó hiểu nào được xác định khi chạy?
Type t = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
object d = Convert.ChangeType("2012-02-23 10:00:00", t);
tôi nhận được thông báo lỗi dưới đây:
Invalid cast from 'System.String' to 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.
Làm thế nào sẽ là độc đáo có thể?
Tôi biết một cách xấu xí sẽ được kiểm tra xem loại là nullable sử dụng nếu:
Type possiblyNullableType = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
var underlyingType = Nullable.GetUnderlyingType(possiblyNullableType);
Object result;
// if it's null, it means it wasn't nullable
if (underlyingType != null)
{
result = Convert.ChangeType("2012-02-23 10:00:00", underlyingType);
}
Nên có bất kỳ cách nào tốt hơn?
Xin cảm ơn,
Tại sao bạn cần kiểm tra t.IsGenericType? phần t.GetGenericTypeDefinition() == typeof (Nullable <>) sẽ bao gồm; phải không? –
@William 'GetGenericTypeDefinition()' ném ngoại lệ nếu loại không phải là chung chung. – hvd