c# - 将字符串转换为类型实例

标签 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; 
        }

最佳答案

var conv = TypeDescriptor.GetConverter(type);
return conv.ConvertFromInvariantString(value);

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

关于c# - 将字符串转换为类型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9434025/

相关文章:

c# - 在 .NET 中使用 wsdl 创建对象

python-3.x - 将 24 位音频转换为 16 位音频的最佳库或方法是什么?

c++ - 用户定义的转换不能在 C++ 中使用 static_cast

C# : How to get area between two series in chart in C#?

javascript - 从 ISO 日期转换为良好的格式化字符串

c# - 为什么我需要显式转换来缩短三元运算符中的整数文字?

java - Vaadin:为 ListSelect 使用自定义转换器

c# - 传递 StringBuilder 并将结果从 c++ dll 返回到 c#

c# - 部分注册为 allowDefinition ='MachineToApplication' 超出应用程序级别

c# - 使用母版页的 Web 应用程序的 ASP.NET 自定义错误页