从String转换为最合适的数据类型

时间:2013-11-11 07:33:16

标签: c# asp.net-mvc-4 reflection

我正在尝试构建一个使用

调用现有方法的动态Web API

GetMethod(String methodName, Type[] Types)

System.Reflection中的

。由于多态性,使用GetMethod(String methodName)的天真方法在调用具有相同名称的方法时失败。

这是我的动态Web API主要方法标题:

public Object API_GET(HttpRequestMessage request)

我像这样阅读request的内容:

    var content = request.Content;
    string contentString = content.ReadAsStringAsync().Result;

字符串contentString现在的结构如下:

"command='aCommand'&param1=1&param2='nnn'" // example

现在我想知道如何使用GetMethod(methodName, Types)根据从上面的字符串中提取的参数调用适当的现有方法

C#中有没有办法将字符串转换为最合适的数据类型?

e.g。

"2"    => Int
"2.0"  => Double
"true" => Bool
"nnn"  => String

2 个答案:

答案 0 :(得分:0)

没有自动的方法来做你想要的,但是编写一系列解析器来尝试你的组合并返回第一个成功的解析器并不难。唯一的缺点是因为您无法提前知道哪个解析器成功返回的类型为object,但您可以使用is operator来测试结果以找出哪种类型它是。

public static class GenericParser
{
    //create a delegate which our parsers will use 
    private delegate bool Parser(string source, out object result);

    //This is the list of our parsers
    private static readonly List<Parser> Parsers = new List<Parser>
    {
        new Parser(ParseInt),
        new Parser(ParseDouble),
        new Parser(ParseBool),
        new Parser(ParseString)
    };

    public static object Parse(string source)
    {
        object result;
        foreach (Parser parser in Parsers)
        {
            //return the result if the parser succeeded.
            if (parser(source, out result))
                return result;
        }

        //return null if all of the parsers failed (should never happen because the string->string parser can't fail.)
        return null;
    }

    private static bool ParseInt(string source, out object result)
    {
        int tmp;
        bool success = int.TryParse(source, out tmp);
        result = tmp;
        return success;
    }

    private static bool ParseDouble(string source, out object result)
    {
        double tmp;
        bool success = double.TryParse(source, out tmp);
        result = tmp;
        return success;
    }

    private static bool ParseBool(string source, out object result)
    {
        bool tmp;
        bool success = bool.TryParse(source, out tmp);
        result = tmp;
        return success;
    }

    private static bool ParseString(string source, out object result)
    {
        result = source;
        return true;
    }
}

Here is a test program

public class Program
{
    static void Main(string[] args)
    {
        TestString("2");
        TestString("2.0");
        TestString("true");
        TestString("nnn");
    }

    static void TestString(string testString)
    {
        object result = GenericParser.Parse(testString);
        Console.WriteLine("\"{0}\"\t => {1}", testString, result.GetType().Name);
    }
}

其输出:

"2"      => Int32
"2.0"    => Double
"true"   => Boolean
"nnn"    => String

答案 1 :(得分:0)

使用动态类型,它会自动转换你的类型。 e.g

    dynamic v1 = 0;
    v1 = 5;
相关问题