我创建了一个扩展函数,它将字符串作为输入并检查值,并根据Generic Type,将其转换为目标类型并返回它,它运行良好。
现在的问题是,如果我将输入值作为空传递它应该返回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。
答案 0 :(得分:4)
然后返回default
值
//Check for empty or null first
if(string.IsNullOrEmpty(value)) return default(T);
//Then your code
var stringType = "System.Nullable`1[[System.{0}, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]";
...
答案 1 :(得分:1)
要回答@mjwills关于创建单独方法的回复,我找到了一个解决方案,让它保持单一方法,并且仍然可以动态处理你抛出的任何类型。
Report path: C:\dev\ws\Seleniumtest\Reports\ExtendReport.html
Screenshot path: "Reports/"+screenName+"-"+dateFormat.format(date)+".jpg";