C # Calling internal methods of an object passed as an interface

I have an IFoo interface that defines some functions, an abstract FooBase class that implements IFoo and some internal functions, and several Foo classes derived from FooBase.
I also have a Bar class that should call a method from FooBase, but gets its parameters passed as IFoo. So, it looks like this:

public interface IFoo
{
  // Some methods
}

public abstract class FooBase : IFoo
{
  // Methods from IFoo

  internal TInternalType SomeMethod();
}

public class Foo1 : FooBase
{
  // ...
}

public class Bar
{
  public void DoSomething(IFoo foo)
  {
    // This does not feel right:
    TInternalType myT = (foo as FooBase).SomeMethod();
  }
}

As already mentioned, this is not so, because anyone can come, write a Baz class that implements IFoo, and calling DoSomething will fail.

/ , , , , IFoo , .. API.

DoSomething, FooBase FooBase , , API, .

, : , (.. ), ?

:
, L . , L , , , , - - L - , .

Foo, , Bar, L. Foo L; Foo , L.

FooBase, Foo L, Bar , , L.

, , .

+4
3

- . , , ( , , , ), . , FooBase.

, DoSomething IFoo. , Bar , , , FooBase IFoo. , .

+1

, IFoo, - IFooWithSomeMethod, SomeMethod FooBase? Bar.DoSomething IFooWithSomeMethod, IFoo.

Btw, , . , .

+3

FooBase - ( decalare IFooWithDoSomething), , IFoo, - :

public static class FooExtensions {
  public static void DoSomething(this IFoo value) {
    FooBase special = value as FooBase;

    if (null != special)
      special.SomeMethod();
  }
}

public class Bar
{
  public void DoSomething(IFoo foo)
  {
    // Extension is called
    foo.SomeMethod();
  }
}
+1

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


All Articles