W
W
WhiteNinja2016-10-07 14:15:15
C++ / C#
WhiteNinja, 2016-10-07 14:15:15

Can the following approach be implemented using Generic types?

Good day!
There is a class and an interface

class Foo : IFoo
{
  // ...
  
  public void Commit() 
  {
    // ...
  }
}

interface IFoo
{
  // Не содержит метод Commit()
  // Но содержит все остальные методы и свойства, которые реализованы в классе Foo
}

There is another class (performing the service function)
class Bar
{
  protected readonly IFoo _foo;
  private Foo _fooSecure
  { 
    get { return _foo; }
  }
  
  public Bar() {
    _foo = new Foo();
  }
  
  public void Commit()
  {
    _fooSecure.Commit();
  }
}

Inheriting from Bar
class BarChild : Bar
{
  public void SomeMethod()
  {
    _foo.Commit(); // Выдаст ошибку, так как у IFoo нет метода Commit. 
          // Это хорошо, этого мы и добивались		
  }
}

Thus, it turns out that it is impossible to call the _foo.Commit () method in all descendants of the Bar class, but at the same time, in the Bar itself, this can be done through the _fooSecure property.
Question:
Is it possible to implement a worse scheme through Generic parameters, so that in the child classes of Bar, it was impossible to get to the .Commit() method? Since each descendant of BarChild has its own type of _foo variable, and it would need to be passed as generic.
For example:
BarChild : Bar<IAppFoo, AppFoo>
... where IAppFoo is needed to use it in BarChild itself, and AppFoo needs to be able to first create the object itself in Bar through new AppFoo(), and secondly, then use the .Commit() method.
Tried in different ways, nothing sensible comes out.
I ask for help and hints on how to design such a seemingly not very complicated scheme.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2016-10-07
@WhiteNinja

interface IFoo
{
  // Не содержит метод Commit()
  // Но содержит все остальные методы и свойства, которые реализованы в классе Foo
}
interface ITransaction
{
    void Commit();
}
class Foo : IFoo, ITransaction
{
  // ...
  
  public void Commit() 
  {
    // ...
  }
}

class Bar<T, TImpl> where TImpl : T, ITransaction, new()
{
  private readonly TImpl _foo;

  protected T Foo {
    get { return _foo; }
  }

  public Bar() {
    _foo = new TImpl();
  }
 
  public void Commit()
  {
    _foo.Commit();
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question