来自另一个对象的MicroRuleEngine值

时间:2013-08-13 12:17:25

标签: c# expression-trees member rule-engine

看了一下在这里找到的MicroRuleEngine:

https://github.com/runxc1/MicroRuleEngine

在其中一个单元测试中,存在以下代码:

        [TestMethod]
    public void ChildPropertyBooleanMethods()
    {
        Order order = this.GetOrder();
        Rule rule = new Rule()
        { 
            MemberName = "Customer.FirstName",
            Operator = "EndsWith",//Regular method that exists on string.. As a note expression methods are not available
            Inputs = new List<object> { "ohn" }
        };
        MRE engine = new MRE();
        var childPropCheck = engine.CompileRule<Order>(rule);
        bool passes = childPropCheck(order);
        Assert.IsTrue(passes);

        order.Customer.FirstName = "jane";
        passes = childPropCheck(order);
        Assert.IsFalse(passes);
    }

将测试Order.FirstName以“ohn”结尾,这么好......但是我如何更改MRE代码,以便不测试字符串litteral,而是测试值另一个对象?有点像:

    Rule rule = new Rule()
        { 
            MemberName = "Customer.FirstName",
            Operator = "EndsWith",//Regular method that exists on string.. As a note expression methods are not available
            Inputs = new List<object> { new MemberValue<SomeClass>(someclass, "PartOfName") }
        };

其中:

class SomeClass {
    string PartOfName {get; set;}
}

class MemberValue<T>(T instance, string memberName) {
    ...
}

我是ExpressionTrees的新手,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:0)

如果要在将名称作为字符串时获取属性的值,请使用reflection:

object GetPropertyValue(object target, string propertyName)
{
    return target.GetType().GetProperty(propertyName).GetValue(target);
}