我有一个 string
和一个 Type
,我想返回转换为该 Type
的 string
值>.
public static object StringToType(string value, Type propertyType)
{
return Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture);
}
这将返回一个我可以在属性设置值调用中使用的对象
:
public static void SetBasicPropertyValueFromString(object target,
string propName,
string value)
{
PropertyInfo prop = target.GetType().GetProperty(propName);
object converted = StringToType(value, prop.PropertyType);
prop.SetValue(target, converted, null);
}
这适用于大多数基本类型,可空类型除外。
[TestMethod]
public void IntTest()
{ //working
Assert.AreEqual(1, ValueHelper.StringToType("1", typeof (int)));
Assert.AreEqual(123, ValueHelper.StringToType("123", typeof (int)));
}
[TestMethod]
public void NullableIntTest()
{ //not working
Assert.AreEqual(1, ValueHelper.StringToType("1", typeof (int?)));
Assert.AreEqual(123, ValueHelper.StringToType("123", typeof (int?)));
Assert.AreEqual(null, ValueHelper.StringToType(null, typeof (int?)));
}
NullableIntTest
在第一行失败:
System.InvalidCastException: Invalid cast from 'System.String' to 'System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.
我很难确定类型是否可以为 null 并更改 StringToType
方法的行为。
我追求的行为:
如果字符串为 null 或为空,则返回 null,否则按照不可为 null 的类型进行转换。
结果
就像 Kirill 的回答一样,只有一次 ChangeType
调用。
public static object StringToType(string value, Type propertyType)
{
var underlyingType = Nullable.GetUnderlyingType(propertyType);
if (underlyingType != null)
{
//an underlying nullable type, so the type is nullable
//apply logic for null or empty test
if (String.IsNullOrEmpty(value)) return null;
}
return Convert.ChangeType(value,
underlyingType ?? propertyType,
CultureInfo.InvariantCulture);
}
最佳答案
您不能对可空类型使用 Convert.ChangeType,因为它不是从 IConvertible 继承的。你应该重写你的方法。
public static object StringToType(string value, Type propertyType)
{
var underlyingType = Nullable.GetUnderlyingType(propertyType);
if(underlyingType == null)
return Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture);
return String.IsNullOrEmpty(value)
? null
: Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture);
}
关于c# - 从字符串转换为任何基本类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13381468/