【问题标题】:TypeConverter cannot convert from System.StringTypeConverter 无法从 System.String 转换
【发布时间】:2012-01-26 00:33:35
【问题描述】:

我正在尝试将字符串转换为其对应的类(即“true”为true)。我得到“TypeConverter 无法从 System.String 转换”。传递的值为“true”。

我是否以错误的方式调用该方法?

public static T ToClass<T>(this IDictionary<string, string> source) where T : class, new()
{
    Type type = typeof(T);
    T ret = new T();

    foreach (var keyValue in source)
    {
        type.GetProperty(keyValue.Key).SetValue(ret, keyValue.Value.ToString().TestParse<T>(), null);
}

    return ret;
}

public static T TestParse<T>(this string value)
{
    return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}

【问题讨论】:

标签: c# parsing type-conversion


【解决方案1】:

问题是您传递给TestParse 方法的T 不是bool 类型,而是您要创建的类的类型。如果将行更改为

public static bool TestParse(this string value)
    {
        return (bool)TypeDescriptor.GetConverter(typeof(bool)).ConvertFromString(value);
    }

它适用于 bool 情况,但显然不适用于其他情况。您需要通过反射获取您要设置的属性的类型并将其传递给TestParse 方法。

public static T ToClass<T>(this IDictionary<string, string> source) where T : class, new()
{
    Type type = typeof(T);
    T ret = new T();

    foreach (var keyValue in source)
    {
        var propertyInfo = type.GetProperty(keyValue.Key);
        propertyInfo.SetValue(ret, keyValue.Value.ToString().TestParse(propertyInfo.PropertyType), null);
    }

    return ret;
}

public static object TestParse(this string value, Type type)
{
    return TypeDescriptor.GetConverter(type).ConvertFromString(value);
}

我还将TestParse 方法从扩展方法更改为普通方法,因为它感觉有点奇怪

【讨论】:

  • 太棒了! :) 非常感谢,圣诞快乐! :)
【解决方案2】:

按照this answer 中的做法进行操作:

return (T)Convert.ChangeType(value, typeof(T));

其中T是目标类型,值是string类型
编辑:这仅适用于IConvertible 实施者...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多