2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Explicit Interface

Posted at

自分が見ているレポのコードリーディングで次のような構文が出てきて何だろう?と思ったので調べてみた。同じメソッド名でこんな定義が出来るのが知らなかった。調べてみると、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.

リソース

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?