Re: a case for multiple inheritance
- From: Tom Spink <tspink@xxxxxxxxx>
- Date: Thu, 21 Jun 2007 05:36:32 +0100
John wrote:
Hi All,
Although C# has Generics, it still does not support the generic
programming paradigm. Multiple inheritance is required to support real
generic programming. Here is a simple design pattern to illustrate this.
Problem:
I need to expose two lists of objects from a high-level class. I would
like to expose these lists as read-only, but require write access
internally.
Solution:
1) Create a generic ProtectedList<T> class which inherits from List<T>
and overrides the write functions (using the new modifier) to change the
access level from public to protected.
2) Inherit both specialized List<T> by the high-level class
Discussion:
While this usage of inheritance does not conform to the "is-a" relation
imposed by the OOP paradigm, it is a simple and easy way to reuse code
in a generic way.
Thanks for any thoughts, and good solutions to this problem in the
existing C# paradigm.
Hi John,
1) Create a generic ProtectedList<T> class which inherits from List<T>
and overrides the write functions (using the new modifier) to change the
access level from public to protected.
Mhm. FYI The 'new' modifier will define a method as hiding a derived one,
however, take a look at this:
public class A
{
public void Foo ()
{
Console.WriteLine("Foo in A");
}
}
public class B : A
{
private new void Foo ()
{
Console.WriteLine("Foo in B");
}
}
public class E
{
public static void Main ()
{
B b = new B();
b.Foo();
}
}
The output of this will be "Foo in A", because the accessible method from A
is called. If you change the scope of 'Foo' in B to public, the output
will be "Foo in B" as is expected. And, even more interestingly, if you
cast b to A and call 'Foo':
((A)b).Foo();
You'll get A's implementation of 'Foo'. So, as you can see, using the new
keyword will not give you the desired effect here.
2) Inherit both specialized List<T> by the high-level classCan you explain this a bit more? I'm not sure why you need multiple
inheritance here. If you want to expose two read-only lists from your
high-level class, you can expose them as properties that return an array of
your list's type, then call the ToArray method of the associated list.
--
Tom Spink
University of Edinburgh
.
- Follow-Ups:
- Re: a case for multiple inheritance
- From: John
- Re: a case for multiple inheritance
- From: John
- Re: a case for multiple inheritance
- References:
- a case for multiple inheritance
- From: John
- a case for multiple inheritance
- Prev by Date: Re: Mounting a "virtual drive"
- Next by Date: Re: Getting data from another website dynamically
- Previous by thread: a case for multiple inheritance
- Next by thread: Re: a case for multiple inheritance
- Index(es):
Relevant Pages
|
Loading