没有自动的方法来做你想做的事,但是编写一系列解析器来尝试你的组合并返回第一个成功的组合并不难。唯一的缺点是因为您无法提前知道哪个解析器成功了返回的类型object
,但是您可以使用is
运算符测试结果以找出它是哪种类型。
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;
}
}
这是一个测试程序
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