本文整理汇总了C#中NCalc.Expression.HasErrors方法的典型用法代码示例。如果您正苦于以下问题:C# Expression.HasErrors方法的具体用法?C# Expression.HasErrors怎么用?C# Expression.HasErrors使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类NCalc.Expression
的用法示例。
在下文中一共展示了Expression.HasErrors方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CanExecuteScript
private bool CanExecuteScript()
{
if (string.IsNullOrWhiteSpace(this.Script.Text))
{
return false;
}
var expression = new Expression(this.Script.Text);
if (expression.HasErrors())
{
this.ScriptError = expression.Error;
return false;
}
else
{
this.ScriptError = string.Empty;
return true;
}
}
示例2: RunSingle
public override string RunSingle(MultiboxFunctionParam args)
{
try
{
string rval;
Expression tmp = new Expression(intToDec.Replace(prefixDec.Replace(args.MultiboxText, PrefixDecHelper), IntToDecHelper), EvaluateOptions.IgnoreCase);
if (tmp.HasErrors())
rval = tmp.Error;
else
{
try
{
rval = ((int)tmp.Evaluate()).ToString("#,##0.#########");
}
catch
{
try
{
rval = ((float)tmp.Evaluate()).ToString("#,##0.#########");
}
catch
{
try
{
rval = ((double)tmp.Evaluate()).ToString("#,##0.#########");
}
catch
{
rval = double.Parse("" + tmp.Evaluate()).ToString("#,##0.#########");
}
}
}
}
return rval;
//return intToDec.Replace(prefixDec.Replace(args.MultiboxText, PrefixDecHelper), IntToDecHelper);
}
catch { }
return "";
}
示例3: Calculate
public ActionResult Calculate(string calculation)
{
dynamic response = new CalculationResult();
Expression expression = new Expression(calculation);
if (expression.HasErrors())
{
response.success = false;
response.errors = expression.Error;
}
try
{
response.result = expression.Evaluate();
response.success = true;
}
catch (Exception ex)
{
response.success = false;
response.errors = ex.Message;
}
return Json(response);
}
示例4: processFormula
private void processFormula()
{
Expression e;
try
{
e = new Expression(Formula);
}
catch (Exception ex)
{
Error(ex.Message);
return;
}
if (e.HasErrors())
{
Error(e.Error);
return;
}
var parameters = new SortedList<int, Tuple<string, Type>>();
var paramSet = new HashSet<string>();
e.EvaluateFunction += delegate(string name, FunctionArgs args)
{
if (!paramSet.Contains(name) && !RESERVED_NAMES.Contains(name))
{
paramSet.Add(name);
parameters.Add(Formula.IndexOf(name), Tuple.Create(name, typeof(Value.Function)));
}
foreach (var p in args.Parameters)
{
p.Evaluate();
}
args.Result = 0;
};
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
if (!paramSet.Contains(name))
{
paramSet.Add(name);
parameters.Add(Formula.IndexOf(name), Tuple.Create(name, typeof(Value.Number)));
}
args.Result = 0;
};
try
{
e.Evaluate();
}
catch { }
InPortData.Clear();
foreach (var p in parameters.Values)
{
InPortData.Add(new PortData(p.Item1, "variable", p.Item2));
}
RegisterInputs();
}
示例5: ShouldDetectSyntaxErrorsBeforeEvaluation
public void ShouldDetectSyntaxErrorsBeforeEvaluation()
{
var e = new Expression("a + b * (");
Assert.IsNull(e.Error);
Assert.IsTrue(e.HasErrors());
Assert.IsTrue(e.HasErrors());
Assert.IsNotNull(e.Error);
e = new Expression("+ b ");
Assert.IsNull(e.Error);
Assert.IsTrue(e.HasErrors());
Assert.IsNotNull(e.Error);
}
示例6: ProcessFormula
private void ProcessFormula()
{
Expression e;
try
{
e = new Expression(
FormulaString.ToLower()
.Replace(" and ", "+").Replace("&&", "+")
.Replace(" or ", "+").Replace("||", "+"),
EvaluateOptions.IgnoreCase);
}
catch (Exception ex)
{
Error(ex.Message);
return;
}
if (e.HasErrors())
{
Error(e.Error);
return;
}
var parameters = new List<string>();
var paramSet = new HashSet<string>();
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
if (!paramSet.Contains(name) && !reservedParamNames.Contains(name))
{
paramSet.Add(name);
parameters.Add(name);
}
args.Result = 0;
};
e.EvaluateFunction += delegate(string name, FunctionArgs args)
{
foreach (var p in args.Parameters)
{
p.Evaluate();
}
args.Result = 0;
};
try
{
e.Evaluate();
}
catch { }
InPorts.Clear();
foreach (var p in parameters)
{
InPorts.Add(new PortModel(PortType.Input, this, new PortData(p, "variable")));
}
ClearRuntimeError();
}
示例7: ProcessFormula
private void ProcessFormula()
{
Expression e;
try
{
e = new Expression(
FormulaString.ToLower()
.Replace(" and ", "+").Replace("&&", "+")
.Replace(" or ", "+").Replace("||", "+"),
EvaluateOptions.IgnoreCase);
}
catch (Exception ex)
{
Error(ex.Message);
return;
}
if (e.HasErrors())
{
Error(e.Error);
return;
}
var parameters = new List<Tuple<string, Type>>();
var paramSet = new HashSet<string>();
e.EvaluateFunction += delegate(string name, FunctionArgs args)
{
if (!paramSet.Contains(name) && !ReservedFuncNames.Contains(name))
{
paramSet.Add(name);
parameters.Add(Tuple.Create(name, typeof(Value.Function)));
}
foreach (var p in args.Parameters)
{
p.Evaluate();
}
args.Result = 0;
};
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
if (!paramSet.Contains(name) && !ReservedParamNames.Contains(name))
{
paramSet.Add(name);
parameters.Add(Tuple.Create(name, typeof(Value.Number)));
}
args.Result = 0;
};
try
{
e.Evaluate();
}
catch { }
InPortData.Clear();
foreach (var p in parameters)
{
InPortData.Add(new PortData(p.Item1, "variable", p.Item2));
}
RegisterInputs();
ClearError();
}
示例8: Formulas
static Formulas()
{
if (DamageModelConfig.Formulas != null)
{
if (!string.IsNullOrEmpty(DamageModelConfig.Formulas.Accuracy))
{
AccuracyExpression = new Expression(DamageModelConfig.Formulas.Accuracy, EvaluateOptions.IgnoreCase);
if (AccuracyExpression.HasErrors())
{
HasErrors = true;
Errors.Add($"Accuracy expression error: {AccuracyExpression.Error}.");
AccuracyExpression = null;
}
else
AccuracyExpression.CutOffUnknownParameters();
}
if (!string.IsNullOrEmpty(DamageModelConfig.Formulas.Alacrity))
{
AlacrityExpression = new Expression(DamageModelConfig.Formulas.Alacrity, EvaluateOptions.IgnoreCase);
if (AlacrityExpression.HasErrors())
{
HasErrors = true;
Errors.Add($"Alacrity expression error: {AlacrityExpression.Error}.");
AlacrityExpression = null;
}
else
AlacrityExpression.CutOffUnknownParameters();
}
if (!string.IsNullOrEmpty(DamageModelConfig.Formulas.Critical))
{
CriticalExpression = new Expression(DamageModelConfig.Formulas.Critical, EvaluateOptions.IgnoreCase);
if (CriticalExpression.HasErrors())
{
HasErrors = true;
Errors.Add($"Critical expression error: {CriticalExpression.Error}.");
CriticalExpression = null;
}
else
CriticalExpression.CutOffUnknownParameters();
}
if (!string.IsNullOrEmpty(DamageModelConfig.Formulas.Surge))
{
SurgeExpression = new Expression(DamageModelConfig.Formulas.Surge, EvaluateOptions.IgnoreCase);
if (SurgeExpression.HasErrors())
{
HasErrors = true;
Errors.Add($"Surge expression error: {SurgeExpression.Error}.");
SurgeExpression = null;
}
else
SurgeExpression.CutOffUnknownParameters();
}
if (!string.IsNullOrEmpty(DamageModelConfig.Formulas.MasteryCritical))
{
MasteryCriticalExpression = new Expression(DamageModelConfig.Formulas.MasteryCritical, EvaluateOptions.IgnoreCase);
if (MasteryCriticalExpression.HasErrors())
{
HasErrors = true;
Errors.Add($"Mastery critical expression error: {MasteryCriticalExpression.Error}.");
MasteryCriticalExpression = null;
}
else
MasteryCriticalExpression.CutOffUnknownParameters();
}
if (!string.IsNullOrEmpty(DamageModelConfig.Formulas.BonusDamage))
{
BonusDamageExpression = new Expression(DamageModelConfig.Formulas.BonusDamage, EvaluateOptions.IgnoreCase);
if (BonusDamageExpression.HasErrors())
{
HasErrors = true;
Errors.Add($"Bonus damage expression error: {BonusDamageExpression.Error}.");
BonusDamageExpression = null;
}
else
BonusDamageExpression.CutOffUnknownParameters();
}
if (!string.IsNullOrEmpty(DamageModelConfig.Formulas.SpellBonusDamage))
{
SpellBonusDamageExpression = new Expression(DamageModelConfig.Formulas.SpellBonusDamage, EvaluateOptions.IgnoreCase);
if (SpellBonusDamageExpression.HasErrors())
{
HasErrors = true;
Errors.Add($"Spell bonus damage expression error: {SpellBonusDamageExpression.Error}.");
SpellBonusDamageExpression = null;
}
else
SpellBonusDamageExpression.CutOffUnknownParameters();
}
}
}
示例9: ExecuteScriptAction
private void ExecuteScriptAction()
{
var expression = new Expression(this.Script.Text);
if (expression.HasErrors())
{
this.ScriptResult = string.Empty;
this.ScriptError = expression.Error;
}
else
{
try
{
foreach (var parameter in this.Parameters.Where(x => !string.IsNullOrWhiteSpace(x.Label)))
{
expression.Parameters.Add(parameter.Label, parameter.Value);
}
this.ScriptResult = expression.Evaluate();
this.ScriptError = string.Empty;
}
catch (Exception ex)
{
this.ScriptError = ex.Message;
this.ScriptResult = string.Empty;
}
}
}
示例10: Calculator
private async Task<string> Calculator(string text)
{
NCalc.Expression exp;
string setString = text;
bool flag = false;
Regex reg = new Regex(@"^\d|\)|\(");
if (text.Length != 0 && reg.IsMatch(text))
{
mode = "calc";
if (text.Substring(text.Length - 1, 1).Equals("="))
{
text = text.Substring(0, text.Length - 1);
flag = true;
}
exp = new NCalc.Expression(text, EvaluateOptions.IgnoreCase);
if (!exp.HasErrors())
{
try
{
setString = exp.Evaluate().ToString();
if (flag)
{
if (!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(() => TextBar1.Text = setString, DispatcherPriority.Normal);
Dispatcher.Invoke(() => TextBar1.Select(TextBar1.Text.Length, 0), DispatcherPriority.Normal);
}
else
{
TextBar1.Text = setString;
//sets cursor
TextBar1.Select(TextBar1.Text.Length, 0);
}
}
}
catch (Exception ex)
{
}
}
else
setString = "Please use a valid expression";
}
return setString;
}
示例11: calcApplicationEnergy
private void calcApplicationEnergy(string path, Expression e, ref double appEnergy)
{
string[] lineValue;
string[] currFile = File.ReadAllLines(path);
string[] varNames = currFile[0].Split(delimiter);
for (int i = 1; i < currFile.Length; i++)
{
lineValue = currFile[i].Split(delimiter);
for (int j = 0; j < varNames.Length; j++)
{
double value = Double.Parse(lineValue[j].ToString());
if (value < 0) value = 0;
e.Parameters[varNames[j]] = value;
}
if (e.HasErrors()) updateStatus("e has error " + e.Error);
try
{
double x = double.Parse(e.Evaluate().ToString());
appEnergy += float.Parse(e.Evaluate().ToString()) / 1000;
}
catch (EvaluationException ee)
{
updateStatus("Error catched: " + ee.Message);
}
}
}
示例12: CreateExpressionFromString
protected ReturnStatus<Expression> CreateExpressionFromString(string expressionStr, EvalType evalType)
{
string formattedExpressionStr;
switch (evalType)
{
case EvalType.ControlPoint:
formattedExpressionStr = EvaluationJob.FUNC_NAME_LIMIT + "(" + expressionStr + ")";
break;
case EvalType.Curve:
formattedExpressionStr = EvaluationJob.FUNC_NAME_LIMIT + "(" +
EvaluationCurveJob.FUNC_NAME_SNAP + "(" + expressionStr + "))";
break;
default:
Debug.Assert(false);
formattedExpressionStr = expressionStr.ToLower();
break;
}
//Even though we use EvaluateOptions.IgnoreCase when we construct an expression
//it still seems to be necessary to convery everything to lower case. Other
//parameters will not be evaluated.
formattedExpressionStr = formattedExpressionStr.ToLower();
Expression expression = null;
if (this.expressionCache.ContainsKey(formattedExpressionStr) == false)
{
expression = new Expression(formattedExpressionStr, EvaluateOptions.IgnoreCase);
//Calling HasErrors() will cause expression.ParsedExpression to be set.
if (expression.HasErrors())
{
//Cache this expression that causes a syntax error as null so that it doesn't have to be parsed again.
this.expressionCache.GetAndAddValue(formattedExpressionStr, () => null);
expression = null;
}
else
{
this.expressionCache.GetAndAddValue(formattedExpressionStr, () => expression.ParsedExpression);
}
}
else
{
//We have already ensured that the key is in the cache so the createValue function should not be called.
LogicalExpression parsedExpression = this.expressionCache.GetAndAddValue(formattedExpressionStr, () => { Debug.Assert(false); return null; });
if (parsedExpression != null) {
expression = new Expression(parsedExpression, EvaluateOptions.IgnoreCase);
}
}
if (expression == null)
{
return new ReturnStatus<Expression>();
}
else {
SetExpressionConstants(expression);
return new ReturnStatus<Expression>(expression);
}
}
示例13: ListParameters
public static List<string> ListParameters(Equation Equ)
{
List<string> param = new List<string>();
Expression ex = new Expression(Equ.EquationText);
ex.EvaluateFunction += delegate(string name, FunctionArgs args)
{
if (name == "Length")
param.Add(args.Parameters[0].ToString());
args.Result = 1;
};
ex.EvaluateParameter += delegate(string name, ParameterArgs args)
{
param.Add(name);
args.Result = 1;
};
if (ex.HasErrors())
MessageBox.Show(ex.Error);
ex.Evaluate();
return param;
}
示例14: Main
//.........这里部分代码省略.........
for (int n = 0; n < numOfTest; n++)
{
string[] sampleFile = File.ReadAllLines(rootPath + (n + 1) + @"\sample.txt");
string[] samVars = sampleFile[0].Split('\t');
if (samVars.Length == 1)
samVars = sampleFile[0].Split(' ');
string[] currFile = File.ReadAllLines(rootPath + (n + 1) + @"\test.txt");
string[] varNames = currFile[0].Split('\t');
if (varNames.Length == 1)
varNames = currFile[0].Split(' ');
Expression e = new Expression(equation);
float energy = 0;
double totalEnergy = 0;
//Calculate total energy (joule)
for (int k = 1; k < sampleFile.Length; k++)
{
string[] sampleValues = sampleFile[k].Split('\t');
if (sampleValues.Length == 1)
sampleValues = sampleFile[k].Split(' ');
double power = double.Parse(sampleValues[sampleValues.Length - 1]) / 1000.0;
totalEnergy += power;
}
//Calculate asynchronous energy (joule)
double asyncTotal = 0;
if (n == 0)
{
string[] asyncFile = File.ReadAllLines(rootPath + (n + 1) + @"\asyncTable.txt");
for (int aNum = 1; aNum < asyncFile.Length; aNum++)
{
string line = asyncFile[aNum];
string[] lines = line.Split('\t');
if (lines.Length == 1)
lines = line.Split(' ');
asyncTotal += (double.Parse(lines[1]) / 1000);
}
}
for (int i = 1; i < currFile.Length; i++)
{
string[] lineValue = currFile[i].Split('\t');
if (lineValue.Length == 1)
lineValue = currFile[i].Split(' ');
for (int j = 0; j < varNames.Length; j++)
{
double value = Double.Parse(lineValue[j].ToString());
if (value < 0) value = 0;
e.Parameters[varNames[j]] = value;
}
if (e.HasErrors())
{
Console.WriteLine("e has error " + e.Error);
}
try
{
double x = double.Parse(e.Evaluate().ToString());
Console.WriteLine(e.Evaluate());
energy += float.Parse(e.Evaluate().ToString())/1000;
}
catch (EvaluationException ee)
{
Console.WriteLine("Error catched: " + ee.Message);
}
}
Console.WriteLine("Test " + (n+1) + " = " + energy);
tw.WriteLine("Test " + (n+1) + " = " + energy);
Console.WriteLine("Total energy = " + totalEnergy);
avgEnergy += energy;
avgTotalEnergy += totalEnergy;
avgAsyncEnergy += asyncTotal;
}
Console.WriteLine("average energy = " + (avgEnergy / numOfTest));
Console.WriteLine("average total energy = " + (avgTotalEnergy / numOfTest));
tw.WriteLine("");
tw.WriteLine("Average energy " + avgEnergy / numOfTest + " joules");
tw.WriteLine("average async energy = " + (avgAsyncEnergy / numOfTest) + " joules");
tw.WriteLine("average total energy = " + (avgTotalEnergy / numOfTest) + " joules");
tw.Close();
//Console.ReadKey();
}