在编译时将字符串转换为未知类型 [英] Convert String to Type unknown at compile time

查看:36
本文介绍了在编译时将字符串转换为未知类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个字符串和一个数字类型,我想检查该字符串是否可以转换为该类型,如果可能,我希望将该字符串转换为该类型.Bellow 是我要执行的操作的 sudo 代码:

Given a string and a type of number, I would like to check if the string can be converted to that type and would like the string to be converted to that type if possible. Bellow is the sudo code for what I am trying to do:

public bool DataIsValid(string s, Type someNumType) {
    d = 0; // a class member double variable

    if (s.CanBeConvertedTo(someNumType)) {
        d = (double)s;
        return true;
    } else {
        return false;
}

我总是试图将字符串转换为某种类型的数字,但我不知道是什么类型.我试过使用 try/catch 块与

I'm always trying to convert a string to some type of number but I don't know what type. I've tried using a try/catch block with

d = (double)Convert.ChangeType(s, someNumType);

但这仅适用于双打.对于整数,我收到错误System.InvalidCastException".

but this only works for doubles. With integers I get the error "System.InvalidCastException".

我认为问题在于在我转换它之后将它转换回双精度(因为它适用于双精度而不是整数).可能

I think the issue is with casting it back to a double after I have converted it (because it works with doubles and not ints). Might

object data = Convert.ChangeType(s, someNumType)
d = (double)data;

工作?

推荐答案

我设法使用以下方法实现了我想要的:

I managed to achieve what I wanted using the following:

public bool DataIsValid(string s, Type someType) {
    o = 0; // a class member object variable

    try { o = Convert.ChangeType(s, someType); }
    catch { return false; }

    return true;
}

//using the object variable
double someDouble = (double)0;
//some more code

感谢您的帮助.

这篇关于在编译时将字符串转换为未知类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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