【发布时间】:2018-03-19 05:59:31
【问题描述】:
我有一个string 和一个Type,我想返回转换为Type 的string 值。
public static object StringToType(string value, Type propertyType)
{
return Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture);
}
这会返回一个object,我可以在属性集值调用中使用它:
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:从 'System.String' 到 'System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' 的无效转换。
我很难确定该类型是否可以为空并更改 StringToType 方法的行为。
我所追求的行为:
如果字符串为null或空,则返回null,否则按照不可为空的类型进行转换。
结果
就像基里尔的回答一样,只有一个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);
}
【问题讨论】:
-
你可以让你的方法通用:
public static object StringToType<T>(string value) where T : struct... -
@KarelFrajtak Na,由于它的调用方式,请参见第二个代码片段。
prop.PropertyType来自反射,所以直到运行时才知道。 -
您的
if支票不太正确。您的特殊情况不应该适用于 any 泛型类型,而应该只是适用于Nullable<T>,因为它们的装箱方式不同。 -
好的,但它也可以是一个选项;)
-
@Servy 是的,我已经更新了。现在基于基里尔的回答。
标签: c#