2

Tried searching online for this but no luck so far

Basically I allow the user create an expression of choices such as

TargetHealthLessThen20 TargetAboutToUsePotion

These are stored against an enum and then stored in database as a string expression such as

"TargetHealthLessThen20 || TargetAboutToUsePotion"

now I have methods for each enum to check its conditon i.e

 public bool IsTargetHealthLessThen20(Target target)
 {
      // do login
 }

 public bool IsTargetAboutToUsePotion(Target target)
 {
     // do login
 }

I want to be able to write an If statement that was dynamic to call these methods and put in the conditons such as

 if("IsTargetHealthLessThen20(target) || IsTargetAboutToUsePotion(target)")
 {
       // Perform Action
 }

Any ideas on best way of going about this?

3 Answers 3

1

While I wouldn't necessarily recommend the following due to performance reasons, it will do what you want.

If you are always applying your target and only your target, you can predefine a class of evaluative methods and then pass in a list of string method names to evaluate against those methods.

void Main()
{
    var inputs = new List<string>();
    inputs.Add("MethodA");
    inputs.Add("MethodB");

    var results = Evaluate(inputs, "target");
    Console.WriteLine(results);
}

public bool Evaluate(List<string> predicates, string target)
{
    var methods = new Methods();

    var tempResult = false;

    foreach (var pred in predicates)
    {
        var method = methods.GetType().GetMethod(pred);
        if (method == null)
        throw new InvalidOperationException(
            string.Format("Unknown method {0}.", pred));

        tempResult = (bool)typeof(Methods).GetMethod(pred).Invoke(methods, new [] {target});
        if (!tempResult) break;

        continue;
    }

    return tempResult;
}

public class Methods
{
    public bool MethodA(string target)
    {
        return target == "target";
    }

    public bool MethodB(string target)
    {
        return target == "not a target";
    }
}

This particular Evaluate function will evaluate AND conditions. You would need to change your evaluative logic for OR conditions. You could in theory inspect your strings and call a different method depending on the operators in the strings.

EDIT

A second option that would avoid reflection would be to create a Dictionary that maps your string names for your methods to the methods themselves. This would allow you to achieve the same result without reflection, although you would have to keep your dictionary in sync. On the flip side, you gain and additional compile-time check without the reflection overhead.

private static readonly Methods _methodsInstance = new Methods();

private static Dictionary<string, Func<string, bool>> _methods = new Dictionary<string, Func<string, bool>>()
{
    { "MethodA", _methodsInstance.MethodA },
    { "MethodB", _methodsInstance.MethodB },
};

public bool Evaluate(List<string> predicates, string target)
{
    var tempResult = false;

    foreach (var pred in predicates)
    {   
        tempResult = _methods[pred](target);
        if (!tempResult) break;
        continue;
    }

    return tempResult;
}
0

I think it's diffcult. Because you don't know the target parameter value. if you know the parameter value, you can use the reflect invoke the method by expression string.

0

I think I have just the answer you're looking for, because I needed the nearly exact same thing in the past:

What you have there is C# code, so you need to treat it like what it is :)

  1. Create an interface like

    interface ICondition { bool Evaluate(); }

  2. Now use the text you have there to compile it into a class. Like this: using YourProgramNamespace; class myCondition : ICondition { bool Evaluate() { return {0} ; } } To pass more parameters just change the interface to allow for the matching parameters. If you don't want multiple interfaces just make it like this:

    using YourProgramNamespace; class myCondition : ICondition { bool Evaluate(params object[] parameters) { return {0} ; } } In your text you then just write it like this: TargetHasLessThan20Hp((TargetType)parameters[0])

Where you replace the {0} with the condition text you already have.

  1. Use the C# compiler to compile the code. http://msdn.microsoft.com/de-de/library/microsoft.csharp.csharpcodeprovider%28v=vs.110%29.aspx There are more than enough tutorials on how to use it and it's usage is not that hard.

  2. When you have compiled the class into a Dll load it and find the type with reflection, this is also not hard and there are tons of tutorials out there. Just use yourAssembly.GetTypes() and go from there

  3. Use Activator.CreateInstance to instantiate the type you have

  4. Then just call the evaluate function and it will return true or false.

  5. For better performance don't compile each time until the condition text actually changes.

Need more info? Just ask and I'll edit my answer or post it in the comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.