Overloading function call operator in C#

前端 未结 7 482
北荒
北荒 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:22

    Check out implicit conversion. Another option would be explict conversion, but then you would need to cast the object type.

    public class A
    {
        public A(int myValue)
        {
            this.MyValue = myValue;
        }
        public int MyValue { get; private set; }
    
        public static implicit operator int(A a)
        {
            return a.MyValue;
        }
        public static implicit operator A(int value)
        {
            return new A(value);
        }
        // you would need to override .ToString() for Console.WriteLine to notice.
        public override string ToString()
        {
            return this.MyValue.ToString();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A t = 5;
            int r = t;
            Console.WriteLine(t); // 5
        }
    }
    

提交回复
热议问题