【发布时间】:2018-06-18 04:51:47
【问题描述】:
我创建了一个扩展函数,它将字符串作为输入并检查值并基于通用类型,将其转换为目标类型并返回它,它运行良好。
现在的问题是,如果我将输入值作为空传递,它应该返回 null,对于可为空的类型,但它只是抛出异常。
例如:如果我想将它转换为日期时间,它会抛出以下异常:
String was not recognized as a valid DateTime
下面是我的代码:
public static class Extension
{
public static T ToNull<T>(this string value)
{
var stringType = "System.Nullable`1[[System.{0}, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]";
if (typeof(T) == typeof(String))
stringType = string.Format(stringType, "String");
if (typeof(T) == typeof(Int32?) || typeof(T) == typeof(Int32))
stringType = string.Format(stringType, "Int32");
if (typeof(T) == typeof(DateTime?) || typeof(T) == typeof(DateTime))
stringType = string.Format(stringType, "DateTime");
if (typeof(T) == typeof(Int64?) || typeof(T) == typeof(Int64))
stringType = string.Format(stringType, "Int64");
Type originalType = Type.GetType(stringType);
var underlyingType = Nullable.GetUnderlyingType(originalType);
return (T)Convert.ChangeType(value, underlyingType ?? originalType);
}
}
这里是我如何访问它:
string s = "";
DateTime? t = s.ToNull<DateTime?>();
Console.WriteLine(t);
对于上述情况,我想返回 null。
【问题讨论】:
-
如果你打算像这样使用
typeof,为什么不写单独的方法呢?ToNullableDateTime等? -
这个问题让人困惑
-
@mjwills,因为我要处理多种类型,所以我需要一个通用函数,您能否提出一种更好的方法来在单个函数中处理多种类型?
-
我不会在单个函数中执行此操作。我会使用多种功能。这种方法的问题是不可能知道支持哪些类型(例如,我不能用
byte?调用它,但是如果不深入研究函数本身的细节就不可能知道)。多个功能解决了这个问题。
标签: c# asp.net generics extension-methods nullreferenceexception