C# Generics won't allow Delegate Type Constraints

前端 未结 8 1284
别跟我提以往
别跟我提以往 2020-11-28 08:01

Is it possible to define a class in C# such that

class GenericCollection : SomeBaseCollection where T : Delegate

I couldn

8条回答
  •  不知归路
    2020-11-28 08:27

    Delegate already supports chaining. Doesn't this meet your needs?

    public class EventQueueTests
    {
        public void Test1()
        {
            Action myAction = () => Console.WriteLine("foo");
            myAction += () => Console.WriteLine("bar");
    
            myAction();
            //foo
            //bar
        }
    
        public void Test2()
        {
            Action myAction = x => Console.WriteLine("foo {0}", x);
            myAction += x => Console.WriteLine("bar {0}", x);
            myAction(3);
            //foo 3
            //bar 3
        }
    
        public void Test3()
        {
            Func myFunc = x => { Console.WriteLine("foo {0}", x); return x + 2; };
            myFunc += x => { Console.WriteLine("bar {0}", x); return x + 1; };
            int y = myFunc(3);
            Console.WriteLine(y);
    
            //foo 3
            //bar 3
            //4
        }
    
        public void Test4()
        {
            Func myFunc = x => { Console.WriteLine("foo {0}", x); return x + 2; };
            Func myNextFunc = x => { x = myFunc(x);  Console.WriteLine("bar {0}", x); return x + 1; };
            int y = myNextFunc(3);
            Console.WriteLine(y);
    
            //foo 3
            //bar 5
            //6
        }
    
    }
    

提交回复
热议问题