コード例 #1
0
ファイル: Program.cs プロジェクト: Anil1111/InteractiveCShap
        static void Main(string[] args)
        {
            MyClass6 myClassOb = new MyClass6();
            //  myClassOb.ShowInterface6();//Error  explicit interface methods
            //MyClass6明确实现了Interface6.ShowInterface6,这时MyClass6的实例无法使用该方法
            Interface6 ob6 = myClassOb;

            ob6.ShowInterface6();

            Console.ReadKey();
        }
コード例 #2
0
        static void Main(string[] args)
        {
            MyClass6 myClassOb = new MyClass6();

            //myClassOb.ShowInterface6();//Error
            ((Interface6)myClassOb).ShowInterface6();//Ok

            /*You can see that we have implemented the interface explicitly.And as per the language specification, to access the
             * explicit interface member we need to use the interface type.So, to overcome the error, you can use following lines of codes*/
            Interface6 ob6 = myClassOb;

            ob6.ShowInterface6();
            Console.ReadKey();
        }
コード例 #3
0
        static void Main(string[] args)
        {
            MyClass6 myClassOb = new MyClass6();

            myClassOb = new MyClass6();
            //MyClass6で明示的にInterface6.ShowInterface6を実装しているため、
            //↓を有効にするとコンパイルエラー
            // 「'MyClass6' に 'ShowInterface6' の定義が含まれておらず、
            //   型 'MyClass6' の最初の引数を受け付けるアクセス可能な拡張メソッド
            //  'ShowInterface6' が見つかりませんでした。
            //   using ディレクティブまたはアセンブリ参照が不足していないかを確認してください。」
            //が発生する
            //言語仕様で明示的に実装されたインターフェースのメンバにアクセスするには、
            //インターフェース型の変数を使って呼び出すことになっているため
            // myClassOb.ShowInterface6();

            //インターフェース型の変数を使って呼び出す例
            Interface6 ob6 = myClassOb;

            ob6.ShowInterface6();

            //キャストしても同様の結果が得られる
            ((Interface6)myClassOb).ShowInterface6();

            //明示的なインターフェースメソッドの実装が
            //  明示的なインターフェイスの真価
            //    2 つ以上の異なるインターフェイスに
            //    同じメソッドシグニチャがあるときに発揮される
            //  必要となるケース
            //    シグニチャは同じでも、目的が異なるような場合
            //    具体的には
            //      - ITriangle とIRectangle の2つのインターフェイスの両方に、
            //        同じシグネチャを持つメソッドBuildMe() が含まれている
            //      - ITriangle.BuildMe() …三角形を生成する
            //      - IRectangle.BuildMe()…四角形を生成する
            //    というような場合、
            //    状況に基づいて適切なBuildMe() メソッドを呼び出せるように、
            //    インターフェイス名を含めて記しておく

            MyChildClass childOb = new MyChildClass();
            Interface6A  ob6A    = childOb;

            ob6A.ShowInterface6();
            Interface6 if6Ob = childOb;

            if6Ob.ShowInterface6();

            Console.ReadKey();
        }