Convert string value to operator in C#

前端 未结 3 994
伪装坚强ぢ
伪装坚强ぢ 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:07

    You can't really do that. The closest you could come would be:

    Func<T, T, bool> ConvertToBinaryConditionOperator<T>(string op)
    

    and then:

    if (ConvertToBinaryConditionOperator<int>(input)(a, b))
    {
    }
    

    The tricky bit is what ConvertToBinaryConditionOperator would do. You might want to look at Marc Gravell's work on implementing generic operators in MiscUtil. Expression trees could be really useful in this case, although I believe Marc has a working approach which works on .NET 2 as well.

    So in this case you might have something like (using MiscUtil)

    public static Func<T, T, bool> ConvertToBinaryConditionOperator<T>(string op)
    {
        switch (op)
        {
            case "<": return Operator.LessThan<T>;
            case ">": return Operator.GreaterThan<T>;
            case "==": return Operator.Equal<T>;
            case "<=": return Operator.LessThanOrEqual<T>;
            // etc
            default: throw new ArgumentException("op");
        }
    }
    
    0 讨论(0)
  • 2020-11-30 13:16

    A more generic way of doing it is to take any IComparable objects.

        public static bool Compare<T>(string op, T left, T right) where T : IComparable<T> {
            switch (op) {
                case "<": return left.CompareTo(right) < 0;
                case ">": return left.CompareTo(right) > 0;
                case "<=": return left.CompareTo(right) <= 0;
                case ">=": return left.CompareTo(right) >= 0;
                case "==": return left.Equals(right);
                case "!=": return !left.Equals(right);
                default: throw new ArgumentException("Invalid comparison operator: {0}", op);
            }
        }
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
提交回复
热议问题