如何在非静态类中使用静态方法
本文关键字:静态方法 静态类 | 更新日期: 2023-09-27 18:33:20
我想在非静态类中使用此方法:
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)
{
}
}
我收到错误
扩展方法必须是静态的
删除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");
}
}