Moh*_*oth 8 c# casting exception-handling
考虑以下功能:
public enum Operator
{
EQUAL = 1,
GREATER_THAN = 2
}
public class checkString
{
public static bool isValid(string inputString, string checkString, Operator operation)
{
switch (operation)
{
case Operator.EQUAL:
if (inputString == checkString)
return true;
break;
case Operator.GREATER_THAN:
// Numeric check for greater than
try
{
double inputDouble, checkDouble;
inputDouble = Convert.ToDouble(inputString);
checkDouble = Convert.ToDouble(checkString);
if (inputDouble > checkDouble)
return true;
}
catch (Exception)
{ }
// Date check for greater than
try
{
DateTime inputDate, checkDate;
inputDate = DateTime.Parse(inputString);
checkDate = DateTime.Parse(inputString);
if (inputDate. > checkDate)
return true;
}
catch (Exception)
{ }
break;
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
参数
其他要知道的事情
问题
在这个过程的任何一点上,我都不知道人们要评估的是什么,但我需要能够检查"某事物"(无论是什么)等于,大于或小于其他东西.当然我检查其他的东西,但我已经大大简化了这个功能.
也就是说,使用EQUAL或NOT_EQUAL可以快速运行,非常快速有效地处理非常大的文件中的记录.一旦我添加了GREATER_THAN逻辑,它的速度很慢......到了需要几分钟才能处理过去需要半分钟时间的20兆字节文件.
据我所知:
是的,我在这个领域缺乏经验,我希望了解更多关于异常处理以及幕后真正发生的事情,因为当其他80%的记录不是数字时,那就是20兆,80中的很多例外.千记录文件.
是否有更好的方法来处理演员本身以提高效率?我见过double.Parse/TryParse并且可以直接在前面投射,但我不确定哪个最有利.
dtb*_*dtb 11
分别使用double.TryParse和DateTime.TryParse而不是Convert.ToDouble和DateTime.Parse.
例:
double result;
if (double.TryParse(someString, out result))
{
Console.WriteLine(result);
}
else
{
// not a valid double
}
Run Code Online (Sandbox Code Playgroud)
您可以对这些数据类型使用TryParse().例外情况既麻烦又昂贵.如果在不抛出异常的情况下,TryParse将返回true/false.所以你可以查看通话结果.比异常更有效率.
Convert.ToDouble()和Double.Parse()将抛出异常.
试试这段代码.它不是最好的,但它比你现在考虑的更好,因为你不知道它的类型是什么:
public static bool isValid(string inputString, string checkString, Operator operation)
{
double dblTmp1;
double dblTmp2;
if (Double.TryParse(inputString, out dblTmp1) && double.TryParse(checkString, out dblTmp2))
{
return Compare<Double>(dblTmp1, dblTmp1, operation);
}
DateTime dtTmp1;
DateTime dtTmp2;
if (DateTime.TryParse(inputString, out dtTmp1) && DateTime.TryParse(checkString, out dtTmp2))
{
return Compare<DateTime>(dtTmp1, dtTmp2, operation);
}
throw new InvalidOperationException("Unknown type");
}
public static bool Compare<T>(T obj1, T obj2, Operator operation) where T : IComparable
{
switch (operation)
{
case Operator.EQUAL:
{
return obj1.Equals(obj2);
}
case Operator.GREATER_THAN:
{
return obj1.CompareTo(obj2) > 0;
}
default:
{
throw new InvalidOperationException("Unknown operation");
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1891 次 |
| 最近记录: |