在嵌套类中使用c#泛型

在嵌套类中使用c#泛型,c#,generics,nested-class,C#,Generics,Nested Class,考虑以下类结构: public class Foo<T> { public virtual void DoSomething() { } public class Bar<U> where U : Foo<T>, new() { public void Test() { var blah = new U(); blah.DoSomethin

考虑以下类结构:

public class Foo<T>
{
    public virtual void DoSomething()
    {
    }

    public class Bar<U> where U : Foo<T>, new()
    {
        public void Test()
        {
            var blah = new U();
            blah.DoSomething();
        }
    }
}

public class Baz
{
}

public class FooBaz : Foo<Baz>
{
    public override void DoSomething()
    {
    }
}
嵌套类的where子句上是否应该有某种方式来表示U始终是父类?怎么做



更新:为上面的DoSomething()添加了一些方法来解决一些注释。重要的是,当我调用DoSomething时,它会处理重写的版本。如果我只是使用Foo而不是U,那么将调用基本实现。

如果
类栏
不需要是泛型的,为什么要将其设为泛型

这将有助于:

public class Foo<T, U> where U : Foo<T, U>
{     
    public class Bar
    {
        private T t;
        private U u;
    }
}

public class Baz
{
}

public class FooBaz : Foo<Baz, FooBaz>
{
}

当然,所有这些都是完全抽象的,因此它可能适用于也可能不适用于实际示例。你到底想在这里实现什么?

不,你不能合并它


在Foo中有T和U,两种不同的类型,编译器不能为U组成一个类型,只能约束它

你为什么要介绍你?你不能用
Foo
替换
Bar
定义中的所有地方吗?

U
在容器类中不可用时,为什么要将其作为泛型参数传递?@SaeedAmiri:因为它可能有用(我添加了类型为
T
U
的字段来提示这一点)。你怎么知道不是呢?好吧,这可能行得通,但我不确定FooBaz定义中的递归。我来试试。好的,这确实有效。但这只是将冗余类型规范移动到父类而不是子类的一种折衷。我的Foo比Bar多得多,所以我想我会让它保持原来的样子。基本上,这个解决方案问的是同样的问题,但是关于自己而不是父母。谢谢。@Jon,如果有用的话,OP应该把它们添加到容器类中,而不是你。我们只需要判断一下我们能看到什么,你如何在
Bar
中使用
U
?用
Foo
代替是不够的吗?我认为你能做的最好的事情就是你现在所做的。Foo不够,因为我可能已经重写了FooBaz中的方法。如果Bar只是引用Foo,它将使用Foo中的基本实现。如果您已经重写了方法,这意味着您还有一个
Foo
的实例,这意味着使用
Foo
作为类型应该起作用。如果
FooBaz
覆盖某些方法,则将调用这些方法。虚拟方法就是这样工作的。如果你说“new Foo()”,你不会仅仅因为定义了一个FooBaz就自动得到一个FooBaz。我会用一些方法更新这个问题,这样你就可以看到了。同样,不行。使用Foo是不够的,因为我可能已经重写了FooBaz中的方法。如果Bar只是指Foo,它使用Foo中的基本实现。因此我问你为什么要介绍U。我希望StackOverflow能让我选择两个公认的答案。确实如此。乔恩的回答更详细一些。无论如何,谢谢你。
var x = new FooBaz.Bar();
public class Foo<T, U> where U : Foo<T, U>
{     
    public class Bar
    {
        private T t;
        private U u;
    }
}

public class Baz
{
}

public class FooBaz : Foo<Baz, FooBaz>
{
}
var bar = new FooBaz.Bar();