Functor overload () for classes

I do not think it is possible and interesting if this is so, or why it is not:

class A
{

}

I would like to consider instances of A as functions such as

A a = new A();

a();
or
a(3);
etc...

This applies to classes as functions for special cases when it is useful. For example, I am essentially wrapping a Func object, but would like to process an instance of a class that will act as the Func object itself. Thus, I do not need to have a "dummy" function to call in the class.


    public class Condition
    {
        protected Func<bool> Eval { get; set; }
        protected bool Or = false;

        protected Condition() { }
        public Condition(Func<bool> f, bool Or = false) { Eval = f; this.Or = Or; }
        protected Func<bool> GetEval(Condition c) { return c.Eval; }
        protected bool GetOr(Condition c) { return c.Or; }

    }

    public class ConditionBlock : Condition
    {
        List<Condition> Conditions;

        public ConditionBlock() { Eval = _Eval; }

        public ConditionBlock(List<Condition> Conditions) : this() { this.Conditions = Conditions; }
        public ConditionBlock(Condition[] Conditions) : this() { this.Conditions = new List<Condition>(Conditions); }
        public void Add(Condition c) { if (Conditions == null) Conditions = new List<Condition>(); Conditions.Add(c); }

        private bool _Eval()
        {
            if (Conditions == null || Conditions.Count == 0) return true;

            bool ans = !GetOr(Conditions[0]);
            for (int i = 0; i < Conditions.Count; i++)
                ans = GetOr(Conditions[i]) ? ans | GetEval(Conditions[i])() : ans & GetEval(Conditions[i])();

            return ans;
        }

        public bool _()
        {
            return Eval();
        }
    }

, (), , cblock.(). , cblock(). ConditionBlock . . _() , - , cblock.fire(), cblock.eval() ..

+3
2

( ).

.

+1

() #, ; , , :

class AccumulateToString
{
    private int sum;
    public string ToString(int val)
    { this.sum += val; return this.sum.ToString(); }
}
var fn = new Converter<int, string>(new AccumulateToString().ToString);
Console.WriteLine(fn(2)); // <-- called like a function but is an object w/ state
+2

Source: https://habr.com/ru/post/1786313/


All Articles