Convert string value to operator in C#

前端 未结 3 1010
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 12:47

Im trying to figure out a way to build a conditional dynamically.

In example

var greaterThan = \">\";
var a = 1;
var b = 2;

if(a Convert.ToOperat         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 13:19

    I wasn't going to post it, but thought that it might be of some help. Assuming of course that you don't need the advanced generic logic in Jon's post.

    public static class Extension
    {
        public static Boolean Operator(this string logic, int x, int y)
        {
            switch (logic)
            {
                case ">": return x > y;
                case "<": return x < y;
                case "==": return x == y;
                default: throw new Exception("invalid logic");
            }
        }
    }
    

    You could use the code like this, with greaterThan being a string with the wanted logic/operator.

    if (greaterThan.Operator(a, b))
    

提交回复
热议问题