检查字符串是否可以转换为 C# 中的给定类型 [英] Check if String can be converted to a given type in C#

查看:18
本文介绍了检查字符串是否可以转换为 C# 中的给定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to validate user input data and ensure a string value is convertible to a type specified at run-time. I don't necessarily need to do the actual conversion, just test to make sure the input value is valid. I haven't found a built in class or method that will perform this type of evaluation, but if I am missing one, please let me know. I'm working with C#4.0, if there is any version specific solutions available.

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

The method only has to deal with the "standard" types (built-in value data types plus String). The only custom type I would need to evaluate is specific enum types that are defined in the library.

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

I have 2 solutions I'm currently weighing, but neither is perfect, so I was hoping there was a 3rd option (or something built into the framework that I missed). I am heavily leaning towards Solution #2 since using the try-catch in Solution #1 just seems wrong.

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

Solution 1: Convert.ChangeType() with 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;
    }
}

解决方案 2 带有类型检查和 TryParse 的 if/else 链

Solution 2 if/else chain with Type check and 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 == typeof(Int32))
    {
        Int32 i;
        return Int32.TryParse(value, out i); 
    }
    else if (type == typeof(Int64))
    {
        Int64 l;
        return Int64.TryParse(value, out l); 
    }
    // similar code to check all other types 
    // (Int16, UInt32, UInt64, UInt16, Byte, SByte, Single, Double, Decimal,
    //  Enum, Char, DateTime)
    .
    .
    .
    .
    .
    else
        throw new ArgumentException("Invalid type evaluation");

}

如果输入数据严重混乱或损坏,此方法可能会在短时间内调用数百甚至数千次,所以我担心重复的 if/else 检查会拖累性能(我'不一定要在这一点上进行优化,我只是想确保我正在考虑其他选项).

This method may be called several hundred or even a thousand times in a short interval if the input data is seriously messed up or corrupted, so I'm worried that the repeated if/else checks will be a drag on performance (I'm not necessarily trying to optimize at this point, I just want to make sure I'm considering other options).

我对这两种解决方案的另一个问题是,它们实际上都将字符串值转换为预期类型的​​新值,并且在这两种情况下,我都在吞下结果.

The other issue I have with both solutions is that both actually convert the string value to a new value of the expected type, and in both cases, I'm swallowing the result.

推荐答案

我在另一个中找到了比我最初的想法更好的解决方案最近提出的问题.

parapura rajkumar 使用 TypeConverter 类走在正确的轨道上,但我试图避免对非异常事件的 CanConvertFrom 方法进行所需的异常处理.

parapura rajkumar was on the right track with the TypeConverter class, but the required exception handling for the CanConvertFrom method for non-exceptional events was what I was trying to avoid.

TypeConverter.IsValid 方法解决了我的问题,虽然它并不理想,因为 IsValid 方法只是 CanConvertFrom 方法和所需异常处理的包装器.

The TypeConverter.IsValid method solved my problem, although it is not ideal because the IsValid method is just a wrapper for the CanConvertFrom method and the required exception handling.

private Boolean CanCovert(String value, Type type)
{
    TypeConverter converter = TypeDescriptor.GetConverter(type);
    return converter.IsValid(value);
}

这篇关于检查字符串是否可以转换为 C# 中的给定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆