Методы расширения и перегрузка [дубликаты]

Вы построили Python из исходного кода? Если это так, вам понадобится опция --with-ssl при создании.

0
задан Joakim Skoog 18 January 2019 в 10:42
поделиться

1 ответ

Мы должны использовать методы расширения , если мы совершенно уверены, что эти методы одинаковы для реализации интерфейса all (включая потенциальную):

  public interface IFoo {
    void Bar(int a); 
  } 

  public static class FooExtensions {
    public static void Bar(this IFoo foo, int a, int b) {...}
    public static void Bar(this IFoo foo, int a, int b, int c) {...}
  }

Мы можем реализовать различные Bar(int a) методы

  public MyFoo : IFoo {
    void Bar(int a) { /* MyFoo algorithm here */}
  }

  public MyOtherFoo : IFoo {
    void Bar(int a) { /* some other - MyOtherFoo - algorithm here */}
  }

Но Bar(int a, b), а также Bar(int a, b, c) все еще остаются прежними:

[112 ]

Если, скажем, Bar(int a, int b) может варьироваться от реализации к реализации, мы должны добавить его в интерфейс:

  public interface IFoo {
    void Bar(int a); 
    void Bar(int a, int b); 
  } 

  ...

  public MyFoo : IFoo {
    void Bar(int a)        { /* MyFoo algorithm here */}
    void Bar(int a, int b) { /* MyFoo algorithm here */} 
  }

  public MyOtherFoo : IFoo {
    void Bar(int a)        { /* some other - MyOtherFoo - algorithm here */}
    void Bar(int a, int b) { /* some other - MyOtherFoo - algorithm here */} 
  }

Если почти все реализации интерфейса имеют тот же алгоритм, что будет скучно вводить код котельной плиты. Однако в C # 8.0 у нас будет хороший компромисс - реализация метода по умолчанию , например

  public interface IFoo {
    void Bar(int a); 
    void Bar(int a, int b) {
      /* Default code here */
    } 
  } 

  // uses default code for Bar(int a, int b)
  public MyFoo : IFoo {
    void Bar(int a)        { /* MyFoo algorithm here */}
  }

  // uses its own code for Bar(int a, int b)
  public MyOtherFoo : IFoo {
    void Bar(int a)        { /* some other - MyOtherFoo - algorithm here */}
    void Bar(int a, int b) { /* some other - MyOtherFoo - algorithm here */} 
  }
0
ответ дан Dmitry Bychenko 18 January 2019 в 10:42
поделиться
Другие вопросы по тегам:

Похожие вопросы: