开发者

Cascading parse

开发者 https://www.devze.com 2023-01-24 12:10 出处:网络
I may have the following types: Number with decimal开发者_如何学C : 100.90 Number (int32) : 32 String : \"\"

I may have the following types:

Number with decimal开发者_如何学C : 100.90

Number (int32) : 32

String : ""

What I want is a function which tries to parse as a decimal and if it fails, then tries to parse as an int and if that fails then its a string. Any sort of function in C# which has the following functionality is appreciated.


public static object cascadeParse(string obj)
{
    decimal decRet;
    if (!decimal.TryParse(obj, out decRet))
    {
        int intRet;
        if (!int.TryParse(obj,  out intRet))
        {
            return obj;
        }
        else
        {
            return intRet;
        }
    }
    else
    {
        return decRet;
    }
}

However this method will always return a decimal when passed something that can be parsed as an int as ints can always be parsed as decimal. You may want to re-order the TryParses to put the int one first.


TryParse() is your friend, however I don't understand what you want as all valid ints are also valid decimals.

0

精彩评论

暂无评论...
验证码 换一张
取 消