相关疑难解决方法(0)

检查String是否可以在C#中转换为给定类型

我必须验证用户输入数据并确保字符串值可以转换为在运行时指定的类型.我不一定需要进行实际转换,只需测试以确保输入值有效.我还没有找到可以执行此类评估的内置类或方法,但如果我遗漏了一个,请告诉我.我正在使用C#4.0,如果有任何特定于版本的解决方案可用.

该方法只需要处理"标准"类型(内置值数据类型加上String).我需要评估的唯一自定义类型是库中定义的特定枚举类型.

我有2个解决方案,我正在权衡,但两者都不是完美的,所以我希望有第三个选项(或者我错过的框架内置的东西).我非常倾向于解决方案#2,因为在解决方案#1中使用try-catch似乎是错误的.

解决方案1:Convert.ChangeType()使用try/catch

public Boolean CheckType(String value, Type type)
{
    try
    {
        var obj = Convert.ChangeType(value, type);
        return true;
    }
    catch(InvalidCastException)
    {
        return false;
    }
    catch(FormatException)
    {
        return false;
    }
    catch(OverflowException)
    {
        return false;
    }
    catch(ArgumentNullException)
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

解决方案2 if/else链接Type Check和TryParse

public Boolean CheckType(String value, Type type)
{
    if (type == typeof(String))
    {
        return true;
    }
    else if (type == typeof(Boolean))
    {
        Boolean b;
        return Boolean.TryParse(value, out b); 
    }
    else if (type == …
Run Code Online (Sandbox Code Playgroud)

c# type-conversion

9
推荐指数
3
解决办法
2万
查看次数

标签 统计

c# ×1

type-conversion ×1