First of all, I would like to say that I am mainly interested in if the following is possible, and I do not intent to actually implement it anywhere soon, and as such bad design is not relevant at this moment. I understand this is easily achieved by using a virtual function.
Question explanation
The following is an example of what I am trying to achieve. It is by no means correct C#.
Say I have a class Foo
which contains an abstract class Bar
, which then contains a function Foobar
. Class Foo
uses this Foobar
function somewhere in a protected function. This is ofcourse not correct C#, as you cannot create an instance of an abstract class.
Class Foo
{
protected abstract class Bar
{
public void Foobar();
}
public void RandomFunction()
{
Bar bar = new Bar();
bar.Foobar();
}
}
I now create a child class of Foo
, named FooChild
. Since Bar
is abstract, FooChild
is forced to override this class.
Class FooChild : Foo
{
override class Bar
{
public void Foobar()
{
Console.WriteLine("This is FooChild.");
}
}
}
Say there is a different part of this program, which requires an instance of class Foo
.
void UseFoo(Foo myFoo)
{
myFoo.RandomFunction();
}
He gets this class via some other function. However, since FooChild is a child of Foo, it can be passed to the function instead.
UseFoo(new FooChild());
The expected outcome of this program would be:
This is FooChild.
My question is, what the correct syntax would be for this, or instead a reasoning why this is not possible.
It's important to remember that C# nested types are a static construct. So the abstract Bar
nested in Foo
does not have any real bearing on subclassing Foo
- the situation would be the same if you instead declared Bar
outside of Foo
(other than the fact it's nested).
This is slightly confused by the fact that when you subclass Foo
with FooChild
, you inherit FooChild.Bar
which is the same as Foo.Bar
- but this is static member inheritance, therefore only really a matter of scope.
Now removing the nesting of Bar
, your question really boils down to the line you notice is invalid C#:
Bar bar = new Bar();
since Bar
is abstract, somebody will need to subclass Bar
in order to create something of that type. You might arrange for this to be passed in from the outside, or created directly in your subclass. Or if you want to force the subclass to also subclass Bar
you could use an abstract factory method on Foo
:
abstract class Foo
{
public abstract Bar CreateBar();
public void RandomFunction()
{
Bar bar = CreateBar();
bar.Foobar();
}
}
Notice that whether your subclass creates the derived Bar
subclass as a nested class or at the top level is irrelevant to this design.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.