Using C # generics in a nested class

Consider the following class structure:

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() { } } 

When I move on to using a nested class, I have something like the following:

 var x = new FooBaz.Bar<FooBaz>(); 

It seems redundant to specify it twice. How would I create my class structure so that I can do this:

 var x = new FooBaz.Bar(); 

Should there be some way in the where clause of a nested class to say that U is always a parent? How?


Update: Added methods for DoSomething () above to consider some comments. It is important that when I call DoSomething, it accesses an overridden version. If I just use Foo instead of U, then the underlying implementation is called instead.

+6
source share
3 answers

If class Bar does not have to be shared, why are you doing it?

This will work:

 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> { } 

And then

 var bar = new FooBaz.Bar(); 

Of course, all this is completely abstract, so it may or may not be applied to a practical example. What exactly are you trying to achieve here?

+3
source

No, you cannot combine this.

Inside Foo, you have T and U, 2 different types, and the compiler cannot compose a type for U, but only restrict it.

+2
source

Why are you typing U at all? Can you replace its use in the entire definition of Bar with Foo<T> ?

0
source

Source: https://habr.com/ru/post/900307/


All Articles