如何比较属性值,包括C#中的比较运算符

时间:2014-10-15 08:15:52

标签: c# xml string

我正在比较两个XML节点,其中包含数字值和比较运算符,如下所示

<rule id="rule1" subject="user1" age="60" permission="granted"/>
<rule id="rule2" subject="user1" age=">=50" permission="denied"/>

这是一个非常简单的例子,其中rule1声明如果主题是user1,那么如果他的年龄是60则授予权限,而规则2声明如果年龄是50或大于50则拒绝user1的权限。所以它意味着这些规则是矛盾的。

我的问题是如何比较包含数值和比较运算符的年龄属性。在上面的例子中,我得出结论,这两个规则都有矛盾的价值。

我正在使用C#来比较这些属性值。

3 个答案:

答案 0 :(得分:0)

在代码中添加runat="server",然后在c#代码中使用rule1.Attributes["age"]访问该属性。如果逻辑需要,可以使用重载运算符进行比较。

答案 1 :(得分:0)

您可能会考虑在代码中执行此操作,使其变得更容易。

    if(age > 50)
permission = "denied";
else if(age == 60)
permission = "granted";

答案 2 :(得分:0)

我将从xml创建一个语法树,并使用树来评估条件。至于如何评估基于比较的规则,您可以编写自己的类,如:

public enum BinaryOperator
{
  LessThenOrEqual,
  LessThen,
  Equal,
  GreaterThen,
  GreaterThenOrEqual
}

public class BinaryOperatorEvaluator
{
  public BinaryOperatorEvaluator(BinaryOperator op)
  {
    Operator = op;
  }

  public BinaryOperator Operator { get; private set; }

  public bool Evaluate(IComparable x, IComparable y)
  {
    switch (Operator)
    {
      case BinaryOperator.Equal:
        return x.CompareTo(y) == 0;
      case BinaryOperator.GreaterThen:
        return x.CompareTo(y) > 0;
      case BinaryOperator.GreaterThenOrEqual:
        return x.CompareTo(y) >= 0;
      case BinaryOperator.LessThen:
        return x.CompareTo(y) < 0;
      case BinaryOperator.LessThenOrEqual:
        return x.CompareTo(y) <= 0;
      default:
        throw new NotImplementedException();
    }
  }

  public static BinaryOperatorEvaluator FromExpression(string expression, out int value)
  {
    var regexValidTerm = new Regex("^(?<operator>(<=|=|>=|<|>)?)(?<numeric>([0-9]+))$");
    var match = regexValidTerm.Match(expression);
    if (!match.Success)
    {
      throw new ArgumentException("Not a valid expression.", "expression");
    }
    var opValue = match.Groups["operator"].Value;
    var op = BinaryOperator.Equal;
    if (!string.IsNullOrEmpty(opValue))
    {
      switch(opValue)
      {
        case "<=":
          op = BinaryOperator.LessThenOrEqual;
          break;
        case "=":
          op = BinaryOperator.Equal;
          break;
        case ">=":
          op = BinaryOperator.GreaterThenOrEqual;
          break;
        case "<":
          op = BinaryOperator.LessThen;
          break;
        case ">":
          op = BinaryOperator.LessThenOrEqual;
          break;
        default:
          throw new NotImplementedException();
      }
    }

    value = int.Parse(match.Groups["numeric"].Value);

    return new BinaryOperatorEvaluator(op);
  }
}


int number;
var bo = BinaryOperatorEvaluator.FromExpression("<=15", out number);
// false
var foo = bo.Evaluate(16, number);
// true
foo = bo.Evaluate(15, number);
// also true
foo = bo.Evaluate(14, number);
相关问题