C# convert a string for use in a logical condition

后端 未结 8 1652
我在风中等你
我在风中等你 2021-01-01 20:40

Is it possible to convert a string to an operator for use in a logical condition.

For example

if(x Convert.ToOperator(\">\") y) {}
8条回答
  •  太阳男子
    2021-01-01 21:36

    EDIT

    As JaredPar pointed out, my suggestion below won't work as you can't apply the operators to generics...

    So you'd need to have specific implementations for each types you wanted to compare/compute...

    public int Compute (int param1, int param2, string op) 
    {
        switch(op)
        {
            case "+": return param1 + param2;
            default: throw new NotImplementedException();
        }
    }
    
    public double Compute (double param1, double param2, string op) 
    {
        switch(op)
        {
            case "+": return param1 + param2;
            default: throw new NotImplementedException();
        }
    }
    

    ORIG

    You could do something like this.

    You'd also need to try/catch all this to ensure that whatever T is, supports the particular operations.

    Mind if I ask why you would possibly need to do this. Are you writing some sort of mathematical parser ?

    public T Compute (T param1, T param2, string op) where T : struct
    {
        switch(op)
        {
            case "+":
                return param1 + param2;
            default:
                 throw new NotImplementedException();
        }
    }
    
    public bool Compare (T param1, T param2, string op) where T : struct
    {
        switch (op)
        {
            case "==":
                 return param1 == param2;
            default:
                 throw new NotImplementedException();
        }
    }
    

提交回复
热议问题