自分が見ているレポのコードリーディングで次のような構文が出てきて何だろう?と思ったので調べてみた。同じメソッド名でこんな定義が出来るのが知らなかった。調べてみると、Explicit Interface という構文っぽい。
async Task<ScaleMetrics> IScaleMonitor.GetMetricsAsync()
{
return await GetMetricsAsync();
}
public Task<KafkaTriggerMetrics> GetMetricsAsync()
:
Explicit Interface の構文を使うと、複数のインターフェイスで同じ名前のメソッドがあっても、インターフェイスを明示した方が使われる。つまりこのケースだと、次のサンプルがわかりやすいかもしれない。同じ GetSome()
のメソッド。1つは、戻り値が int
もう一つの Explicit Interface がついている方の戻りは、string
インターフェイスを介してアクセスすると、該当の Interface の メソッドが呼ばれる。
class Program : IInterface
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var p = new Program();
// int GetSome() is for common usage.
int a = p.GetSome();
IInterface i = new Program();
// If you use interface, it will explicit interface.
string b = i.GetSome();
}
public int GetSome()
{
return 1;
}
string IInterface.GetSome()
{
return "hello";
}
}
interface IInterface
{
string GetSome();
}
一つ実験してみる。インターフェイスに、Hello
メソッドを足す。
interface IInterface
{
string GetSome();
void Hello();
}
Program
に、Hello
メソッドを別途定義する
void Hello()
{
Console.WriteLine("Hello from the class.");
}
void IInterface.Hello()
{
Console.WriteLine("Hello from the interface.");
}
メインメソッドを 変更して、それぞれ Hello()
が呼ばれるようにする。
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var p = new Program();
// int GetSome() is for common usage.
int a = p.GetSome();
p.Hello();
IInterface i = new Program();
// If you use interface, it will explicit interface.
string b = i.GetSome();
i.Hello();
}
Result
予想通り!
Hello World!
Hello from the class.
Hello from the interface.