Generic class with self-referencing type constraint

后端 未结 3 986
感动是毒
感动是毒 2020-12-05 10:51

Consider the following code:

abstract class Foo
    where T : Foo, new()
{
    void Test()
    {
        if(Bar != null)
            Bar(th         


        
3条回答
  •  -上瘾入骨i
    2020-12-05 11:51

    delegate void Bar(Foo foo) where T : Foo, new();
    

    It works great. I tested it.

    here is the test code

    public abstract class Foo where T :Foo {
        public event Bar Bar;
    
        public void Test ()
        {
            if (Bar != null)
            {
                Bar (this);
            }
        }
    }
    
    public class FooWorld : Foo {
    }
    
    public delegate void Bar(Foo foo) where T : Foo;
    
    class MainClass
    {
        public static void Main (string[] args)
        {
            FooWorld fw = new FooWorld ();
            fw.Bar += delegate(Foo foo) {
                Console.WriteLine ("Bar response to {0}", foo);
            };
    
            fw.Test ();
        }
    }
    

提交回复
热议问题