C# Convert string to operator

前端 未结 1 511
天涯浪人
天涯浪人 2021-01-26 10:57

I want to convert string to operator in c#

        **string type = \"+\";
        int d = 22;
        int c = 33;
        int total;
        total = d + type +          


        
1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-26 11:40

    You cannot convert a string to an "operator". An operator is defined for its operands and it doesn't really make sense to convert a string to an operator if you don't know what your operands are.

    Supposing you do know what operands you have, the problem is no longer one of "conversion" per se but actually you are trying to build a parsing engine. This is a problem of considerable difficulty. Unless you actually are trying to create your own scripting language or something of this nature, it is probably just easier to use a lookup table, with each element in the table referring to some method that can be run on the operands.

    In C# it is possible to implement such a data structure using a simple switch statement (of course you can make this as fancy as you want ad infinitum but this is the simplest solution).

    switch( type )
    {
        case "+":
            return plusOperator(d, c);
        case "-":
            return minusOperator(d, c);
    }
    

    Then you would define suitable methods such as plusOperator and minusOperator to actually implement the logic of your program.

    This solution is reasonably dirty in that you are hard-coding certain behaviour but really if you want much more than this in terms of good system architecture it becomes a parsing problem. Should you go down this path the Gang of Four design patterns will make for good reference material (particularly patterns such as the Interpreter, Iterator and Composite)

    0 讨论(0)
提交回复
热议问题