Generic class with self-referencing type constraint

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

Consider the following code:

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


        
3条回答
  •  青春惊慌失措
    2020-12-05 11:37

    You can cast 'this' to T:

    Bar((T)this);
    

    This however will fail if you have the following:

    public class MyFoo : Foo { }
    
    public class MyOtherFoo : Foo { }
    

    Because 'MyOtherFoo' is not an instance of 'MyFoo'. Take a look at this post by Eric Lippert, one of the designers of C#.

提交回复
热议问题