Overloading function call operator in C#

前端 未结 7 485
北荒
北荒 2020-12-01 13:56

Is it possible to overload the default function operator (the () operator) in C#? If so - how? If not, is there a workaround to create a similar affect?

Thanks,

7条回答
  •  一生所求
    2020-12-01 14:42

    Yes, this can be absolutely be done with the dynamic type (more info found here).

    using System.Dynamic.DynamicObject
    
    class A : DynamicObject 
    {
        private int val;
    
        A(int myvalue)
        {
            this.val = myvalue;
        }
    
        public override bool TryInvoke(InvokeBinder binder, object[] args, out object result) {
            result = this.val;
            return true;
        }
    }
    
    ...
    
    dynamic a = new A(5);
    Console.Write(a());
    

    The dynamic type means that the type is assumed entirely at runtime allowing for a greater flexability to almost every interaction with the object.

    I have assumed you meant to use a rather than A in the Console.Write line.

提交回复
热议问题