在c#中有没有办法让类型包含它自己?

在c#中有没有办法让类型包含它自己?,c#,generics,C#,Generics,一种编写我想要的代码的方法是如下所示,但我真的不喜欢这种新的隐藏方式 public class Bar { public TReturn Baz<TReturn>() where TReturn : Bar { return this as TReturn; } } public class Foo : Bar { public new TReturn Baz<TReturn>() where TR

一种编写我想要的代码的方法是如下所示,但我真的不喜欢这种新的隐藏方式

public class Bar
{
    public TReturn Baz<TReturn>()
      where TReturn : Bar
    {
        return this as TReturn;
    }
}

public class Foo : Bar
{
    public new TReturn Baz<TReturn>()
      where TReturn : Foo
    {
        return base.Baz<TReturn>() as TReturn;
    }
}

class Test
{
    public void Main()
    {
      var foo = new Foo();
      var foo2 = foo.Baz<Foo>();
      Assert.IsInstanceOfType(foo.GetType(), foo2);
    }
}
公共类栏
{
公共交通
去哪里:酒吧
{
将此作为TReturn返回;
}
}
公开课Foo:Bar
{
公共新街
特瑞:福在哪里
{
将base.Baz()作为TReturn返回;
}
}
课堂测试
{
公共图书馆
{
var foo=new foo();
var foo2=foo.Baz();
Assert.IsInstanceOfType(foo.GetType(),foo2);
}
}
相反,我想知道泛型类型是否可以包含自身?类似下面的内容

public class Bar<TReturn>
    where TReturn : Bar<TReturn>
{
    public TReturn Baz()
    {
        return this as TReturn;
    }
}

public class Foo<TReturn> : 
    Bar<TReturn>
    where TReturn : Bar<TReturn>
{
}

class Test
{
    public void Main()
    {
      var foo = new Foo<???>();
      var foo2 = foo.Baz();
      Assert.IsInstanceOfType(foo.GetType(), foo2);
    }
}
公共类栏
去哪里:酒吧
{
公共交通
{
将此作为TReturn返回;
}
}
公开课Foo:
酒吧
去哪里:酒吧
{
}
课堂测试
{
公共图书馆
{
var foo=new foo();
var foo2=foo.Baz();
Assert.IsInstanceOfType(foo.GetType(),foo2);
}
}

您应该看看这个:
他对这个模式进行了深入的解释,它是

的一个变体,感谢狗耳朵提供了这个模式的名称和最初的提示

作为参考,我当前的解决方案是清理Foo,这样它就不需要传入类型

public class Bar<TReturn>
    where TReturn : Bar<TReturn>
{
    public TReturn Baz()
    {
        return this as TReturn;
    }
}

public class Foo : Bar<Foo>
{
}

class Test 
{
    public void Main()
    {
        var foo = new Foo();
        var foo2 = foo.Baz();
        Assert.IsInstanceOfType(foo.GetType(), foo2);
    }
}
公共类栏
去哪里:酒吧
{
公共交通
{
将此作为TReturn返回;
}
}
公开课Foo:Bar
{
}
课堂测试
{
公共图书馆
{
var foo=new foo();
var foo2=foo.Baz();
Assert.IsInstanceOfType(foo.GetType(),foo2);
}
}