c# - 从字符串转换为任何基本类型

标签 c#

我有一个 string 和一个 Type,我想返回转换为该 Typestring 值>.

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/

相关文章:

c# - Persist Security Info Property=true 和 Persist Security Info Property=false

c# - 出现错误 -2147220472(无法启动 Quickbooks)

c# - 如何在 phantomjsdriver selenium c# 中启用 cookie?

c# - 如何替换字符串中的单词

c# - 如何在 Windows 服务中显示窗体。

c# - MediatR CQRS - 如何处理不存在的资源(asp.net 核心 web api)

c# - 数据绑定(bind)不适用于 Avalondock 窗口

c# - 如何为HMACSHA256签名计算生成随 secret 钥

C# 窗体 : Relative position of growing elements c# windows forms

c# - 处理json反序列化错误