C#中类型的默认值
Default value of a Type in C#
我正在使用以下代码将字符串转换为任何类型。我在这里将类型硬编码为 double,但它可以是整数或长整数、布尔值或 ...
现在,当字符串为空或 null 时,此代码失败,在这种情况下,我如何 return 传递类型的 default 值?
var result = ConvertFromString(item, typeof(double));
private object ConvertFromString(string str, Type type)
{
return Convert.ChangeType(str, type);
}
我会让你的方法泛化到 return 实际请求的类型而不是对象,以提高类型安全性。您也会在下面找到默认内容的实际答案。
[TestMethod]
public void MyTestMethod()
{
// to be sure that the decimal sign below is "." and not e.g. "," like in my culture :)
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
// test
var result = ConvertFromString<double>("3.14");
Assert.AreEqual(3.14, result);
// test
result = ConvertFromString<double>("blabla");
Assert.AreEqual(0, result);
}
private TRet ConvertFromString<TRet>(string str)
{
TRet ret = default(TRet);
try
{
ret = (TRet)Convert.ChangeType(str, typeof(TRet));
}
catch (Exception ex)
{
// handle error as you wish
}
return ret;
}
您可以使用 Activator.CreateInstance
创建值类型的实例:
private static object ConvertFromString(string str, Type type)
{
if (string.IsNullOrEmpty(str))
return type.IsValueType ? Activator.CreateInstance(type) : null;
return Convert.ChangeType(str, type);
}
ConvertFromString(null, typeof(int))
将 return 0
(或 default(int)
)。
我正在使用以下代码将字符串转换为任何类型。我在这里将类型硬编码为 double,但它可以是整数或长整数、布尔值或 ...
现在,当字符串为空或 null 时,此代码失败,在这种情况下,我如何 return 传递类型的 default 值?
var result = ConvertFromString(item, typeof(double));
private object ConvertFromString(string str, Type type)
{
return Convert.ChangeType(str, type);
}
我会让你的方法泛化到 return 实际请求的类型而不是对象,以提高类型安全性。您也会在下面找到默认内容的实际答案。
[TestMethod]
public void MyTestMethod()
{
// to be sure that the decimal sign below is "." and not e.g. "," like in my culture :)
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
// test
var result = ConvertFromString<double>("3.14");
Assert.AreEqual(3.14, result);
// test
result = ConvertFromString<double>("blabla");
Assert.AreEqual(0, result);
}
private TRet ConvertFromString<TRet>(string str)
{
TRet ret = default(TRet);
try
{
ret = (TRet)Convert.ChangeType(str, typeof(TRet));
}
catch (Exception ex)
{
// handle error as you wish
}
return ret;
}
您可以使用 Activator.CreateInstance
创建值类型的实例:
private static object ConvertFromString(string str, Type type)
{
if (string.IsNullOrEmpty(str))
return type.IsValueType ? Activator.CreateInstance(type) : null;
return Convert.ChangeType(str, type);
}
ConvertFromString(null, typeof(int))
将 return 0
(或 default(int)
)。