将字符串转换为类型实例

Sai*_*aid 3 c# type-conversion

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

        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; 
        }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 7

var conv = TypeDescriptor.GetConverter(type);
return conv.ConvertFromInvariantString(value);
Run Code Online (Sandbox Code Playgroud)

如果您不想要"不变",则存在其他转换操作.这取决于您的需求.另请参阅ConvertFromString是否要将区域设置设置为适用等.


C.E*_*uis 6

你提到你已经尝试过这Convert门课,但你也试过了Convert.ChangeType(value, type)吗?您遇到的问题在哪里?