我想在非静态类中使用此方法:
public class LogicalExpressionCalculator : MeasurementInterpreter
{
private static Boolean Operator(this string logic, string x, string y)
{
switch (logic)
{
case "==": return x == y;
case "!=": return x != y;
case ">": return Int32.Parse(x) > Int32.Parse(y);
case ">=": return Int32.Parse(x) >= Int32.Parse(y);
case "<": return Int32.Parse(x) < Int32.Parse(y);
case "<=": return Int32.Parse(x) <= Int32.Parse(y);
case "&&": return bool.Parse(x) && bool.Parse(y);
case "||": return bool.Parse(x) || bool.Parse(y);
default: throw new Exception("invalid logic");
}
}
}
如何将此方法更改为在非静态类中工作?
我希望在此方法的类中使用的方法:
protected void CalculateExpression()
{
Stack variableStack = new Stack();
Stack operatorStack = new Stack();
foreach (string field in contextString)
{
switch (field)
{
case "(":
case "<":
case ">":
case "==":
operatorStack.Push(field);
break;
case ")":
string operatorPop = null;
while (operatorPop == "(")
{
operatorPop = operatorStack.Pop().ToString();
resultStack = Operator(operatorPop, variableStack.Pop().ToString(), variableStack.Pop().ToString());
variableStack.Push(resultStack);
}
break;
case "UserInput":
case "EngineRpm":
case "VehicleSpeed":
variableStack.Push((string)hashtable[field]);
break;
default:
int integer;
if(Int32.TryParse(field, out integer)) variableStack.Push(integer);
if (bool.Parse(field)) variableStack.Push(field);
break;
}
}
Result = resultStack;
if (Result)
{
}
}
我收到错误
扩展方法必须是静态的
答案 0 :(得分:1)
似乎没有必要删除this
。
private static Boolean Operator(string logic, string x, string y)
{
switch (logic)
{
case "==": return x == y;
case "!=": return x != y;
case ">": return Int32.Parse(x) > Int32.Parse(y);
case ">=": return Int32.Parse(x) >= Int32.Parse(y);
case "<": return Int32.Parse(x) < Int32.Parse(y);
case "<=": return Int32.Parse(x) <= Int32.Parse(y);
case "&&": return bool.Parse(x) && bool.Parse(y);
case "||": return bool.Parse(x) || bool.Parse(y);
default: throw new Exception("invalid logic");
}
}