通常情况下,当我尝试这样做时,是因为我想设置我的属性或将其保留为默认值。借助
此答案和
dynamic
类型,我们可以轻松地创建一个字符串扩展方法,使其保持单行和简单。
public static dynamic ParseAny(this string text, Type type)
{
var converter = TypeDescriptor.GetConverter(type);
if (converter != null && converter.IsValid(text))
return converter.ConvertFromString(text);
else
return Activator.CreateInstance(type);
}
使用方法如下:
bd.Budget = objReader[i].ToString().ParseAny(typeof(double));
int intTest = "1234".ParseAny(typeof(int));
double doubleTest = "12.34".ParseAny(typeof(double));
decimal pass = "12.34".ParseAny(typeof(decimal));
decimal fail = "abc".ParseAny(typeof(decimal));
string nullStr = null;
decimal failedNull = nullStr.ParseAny(typeof(decimal));
可选项
另外,如果使用的是SQLDataReader
,您还可以利用GetSafeString
扩展来避免从reader中得到null例外。
public static string GetSafeString(this SqlDataReader reader, int colIndex)
{
if (!reader.IsDBNull(colIndex))
return reader.GetString(colIndex);
return string.Empty;
}
public static string GetSafeString(this SqlDataReader reader, string colName)
{
int colIndex = reader.GetOrdinal(colName);
if (!reader.IsDBNull(colIndex))
return reader.GetString(colIndex);
return string.Empty;
}
使用方法如下:
bd.Budget = objReader.GetSafeString(i).ParseAny(typeof(double));
bd.Budget = objReader.GetSafeString("ColumnName").ParseAny(typeof(double));
DataGrid
,但后来才知道它只能自动执行属性。将其转换为属性破坏了我在字段上使用的一些ref参数。我必须定义局部变量来进行解析。 - jxramos