【问题标题】:Convert Strings to Type Instances将字符串转换为类型实例
【发布时间】:2012-02-24 16:08:32
【问题描述】:

你有这些代码的替代品吗,我想要一个更通用的代码 我尝试了转换类,但没有成功

        public object convert(Type type, string value)
        {
            object r = null;
            if (type == typeof(bool))
            {
                r = bool.Parse(value);
            }            
            else if (type == typeof(int))
            {
                r = int.Parse(value);
            }
            else if (type == typeof(string))
            {
                r = value;
            }

            return r; 
        }

【问题讨论】:

  • 可能会有很大的变化,但你可以(同时提出其他问题)通过使用动态来摆脱整个问题。

标签: c# type-conversion


【解决方案1】:
var conv = TypeDescriptor.GetConverter(type);
return conv.ConvertFromInvariantString(value);

如果您不想要“不变”,则存在其他转换操作。这取决于您的需求。如果您希望应用区域设置等,另请参阅ConvertFromString。

【讨论】:

    【解决方案2】:

    您提到您尝试过Convert 课程,但您是否也尝试过Convert.ChangeType(value, type)?你遇到了什么问题?

    【讨论】:

    • 是的,我已经尝试过这些,但是我无法投射结果的问题
    • 该方法的结果返回为object,就像您的方法一样。在某些时候,您将不得不像您的示例中那样经历一堆ifs。不幸的是,您不能在类型上 switch。
    【解决方案3】:

    创建一个字典Dictionary<Type, Func<string, object>>怎么样?

    可能是这样的:

    public static class MyConverter
    {
        private static Dictionary<Type, Func<string, object>> _Converters;
    
        static MyConverter()
        {
            _Converters = new Dictionary<Type, Func<string, object>>();
    
            // Add converter from available method
            _Converters.Add(typeof(double), MySpecialConverter);
            // Add converter as lambda
            _Converters.Add(typeof(bool), (text) => bool.Parse(text));
            // Add converter from complex lambda
            _Converters.Add(typeof(int), (text) =>
            {
                if (String.IsNullOrEmpty(text))
                {
                    throw new ArgumentNullException("text");
                }
    
                return int.Parse(text);
            });
        }
    
        private static object MySpecialConverter(string text)
        {
            return double.Parse(text);
        }
    
        public static object Convert(Type type, string value)
        {
            Func<string, object> converter;
    
            if (!_Converters.TryGetValue(type, out converter))
            {
                throw new ArgumentException("No converter for type " + type.Name + " available.");
            }
    
            return converter(value);
        }
    }
    

    【讨论】:

      【解决方案4】:

      Convert.ChangeType() 方法不能转换为可空类型,Guid、Enums 等。implementation of ChangeType 将全部转换。

      【讨论】:

        猜你喜欢
        • 2017-10-09
        • 2018-01-13
        • 2015-06-07
        • 1970-01-01
        • 1970-01-01
        • 2020-05-21
        • 1970-01-01
        • 2010-09-20
        • 1970-01-01
        相关资源
        最近更新 更多