Interface and class inheritance. Is this a template to avoid?

I would appreciate any advice on how to proceed in the following scenario. Let's see if I can explain this (English is not my native language, so everything can get confused, sorry).

Suppose I have the following interfaces:

internal interface IBlah
{
     int Frob();
}

internal interface IBlahOnSteroids: IBlah
{
     double Duh();
}

Now we have a Foo class with a 'has' relation to an IBlah object:

public class Foo
{
     IBlah blah;

     internal Foo(IBlah blah)
     {
          this.blah = blah;
     }

     public int Frob()
     {
          ....
          return this.blah.Frob();
     }
}

Now we also need the FooOnSteroids class, which has a "has" relationship to the IBlahOnSteroids object. The question is, knowing that part of IBlahOnSteroids is already implemented in Foo, what happens if we create FooOnSteroids that inherits from Foo?

We would get something like this:

public class FooOnSteroids: Foo
{
    IBlahOnSteroids blah;

    internal FooOnSteroids(IBlahOnSteroids blah)
        :base(blah) 
    {
         this.blah = blah;
    }

    public double Duh()
    {
         return this.blah.Duh();
    }
}

? "", "" "" . , , BlahBase , IBlah , IBlah, BlahOnSteroids. ? Foo FooOnSteroids ( )? , , - . ?

, , , , , , , .NET 1.x.

BlahOnSteroids , , , , - IBlahOnSteroids. .

!

+3
4

, :

IBlah blah;
protected IBlah Blah { get { return blah; } }

( , blah ):

public double Duh() {
    return ((IBlahOnSteroids)Blah).Duh();
}

- ( ), , . , , , blah ( ).

+2

-

public class Foo
{
    protected IBlah Blah { get; private set; }
    ...
}
public class FooOnSteroids : Foo 
{
    private new IBlahOnSteroids Blah { get { return (IBlahOnSteroids)base.Blah; } }
    ...
}

; , .

+2

Foo FooOnSteroids, , . FooOnSteroids, Foo.

, :

Foo foo = new FooOnSteroids();
foo.Frob()

.

, , , . .

+1

, ( ), blah Foo. # :

public double Duh()
{
    return (this.blah as IBlahOnSteroids).Duh();
}

A keyword asin C # will be evaluated before nullif the object cannot be entered in the type you requested. In the above example, if this.blahnot an instance IBlahOnSteroids, you will get NullReferenceException. You can check if the object is an instance of this type:

public double Duh()
{
    if (this.blah is IBlahOnSteroids)
        return (this.blah as IBlahOnSteroids).Duh();
    else
        throw new InvalidTypeException("Blah is not an instance of IBlahOnSteroids");
}

Although the code in your source example should blahnot be an instance IBlahOnSteroids, since it is assigned in the constructor, which makes this statement at compile time for you.

+1
source

All Articles