【发布时间】:2013-10-24 22:08:05
【问题描述】:
抱歉,我不得不重新编辑这个问题。
我需要将两个字符串值动态解析为合适的类型并进行比较,然后返回一个bool结果。
示例 1:
string lhs = “10”;
string rhs = “10”;
Compare.DoesEqual(lhs, rhs, typeof(int)); //true
Compare.DoesEqual(lhs, rhs, typeof(string)); //true
示例 2:
string lhs = “2.0”;
string rhs = “3.1”;
Compare.IsGreaterThan(lhs, rhs, typeof(int)); //false
Compare.IsGreaterThan(lhs, rhs, typeof(double)); //false
Compare.IsGreaterThan(lhs, rhs, typeof(string)); //invalid, always false
目前我正在这样做(我认为这样做很愚蠢):
public partial class Comparer
{
public static bool DoesEqual(string lhs, string rhs, Type type)
{
if (type.Equals(typeof(int)))
{
try
{
return int.Parse(lhs) > int.Parse(rhs);
}
catch
{
return false;
}
}
if (type.Equals(typeof(double)))
{
try
{
return double.Parse(lhs) > double.Parse(rhs);
}
catch
{
return false;
}
}
return false;
}
}
还有这个:
public partial class Comparer
{
public static bool IsGreaterThan(string lhs, string rhs, Type type)
{
if (type.Equals(typeof(int)))
{
try
{
return int.Parse(lhs) == int.Parse(rhs);
}
catch
{
return false;
}
}
if (type.Equals(typeof(double)))
{
try
{
return double.Parse(lhs) == double.Parse(rhs);
}
catch
{
return false;
}
}
if (type.Equals(typeof(string)))
{
return lhs.Equals(rhs);
}
return false;
}
}
我正在寻找更好的更好(更通用的方式)实现(也许使用表达式树?)。我很感激任何建议。谢谢!
【问题讨论】:
-
Thyis 不清楚:
Compare.IsGreaterThan(lhs, rhs, typeof(string)); //invalid, always false。为什么总是假的?一个字符串总是可以转换成字符串,两个字符串可以比较(字母排序,所以"2.0"
标签: c# parsing compare dynamic