Free Web Hosting by Netfirms
Web Hosting by Netfirms | Free Domain Names by Netfirms

  
 

Interface

        Interface คือ การกำหนดความสามารถของ object ใน OOP ซึ่ง class ใด implement interface ก็เป็นการสัญญาว่าจะมีความสามารถตามที่ interface กำหนดไว้ พูดง่ายๆก็คือ เป็นการแยก specification ออกจาก ส่วน implementation ของ class นั่นเอง ดังนั้นการติดต่อกับ object ที่สร้างขึ้นจาก class ดังกล่าวต้องผ่าน interface เท่านั้น

      C# สนับสนุนการทำงานแบบ inerface โดยใช้ keyword interface

using System;

interface IMath{
    int
add ( int x, int y );
}

class Math : IMath
{
    public int
add(int x, int y)
    {
        return
x+y;
    }
}

class Test
{
    public static void
Main()
    {
        Math m
= new Math();
        IMath im
= new IMath;
        im
= m;
        Console
.WriteLine ("The result is " + im.add( 5 ,6 ));
    }
}

output :

The result is 11

 

interface นั้นเป็น abstract data type ซึ่งไม่สามารถ instantiate ได้ การใช้งานจะต้องสร้าง object ก่อน (เช่น Math) แล้ว ให้ reference ของ interface ชี้ไปยัง object นั้น

class หลายๆ class สามารถ implement interface เดียวกันได้ โดยแต่ละ class ก็มีส่วน implementation แตกต่างกันไป ซึ่งการเรียก method ของ interface จะขึ้นอยู่กับ ชนิดของ object ที่ interface ผูกติดอยู่ หมายความว่า interface สามารถทำ polymorphism ได้ เช่น เดียวกับกลไกของ virtual function ของ class ธรรมดานั่นเอง

using System;
interface Shape{
    void
draw();
}
class Circle : Shape
{
    public void
draw()
    {
        Console
.WriteLine("draw circle");
    }
}
class Triangle : Shape
{
    public void
draw()
    {
        Console
.WriteLine("draw shape");
    }
}
class Test
{
    public static void
Main()
    {
    Shape shape
;
    Circle circle
= new Circle();
    Triangle triangle
= new Triangle();
    shape
= circle;
    shape
.draw();
    shape
= triangle;
    shape
.draw();
    }
}

output :

draw circle

draw shape

polymorphism เกิดขึ้นได้เพราะเมื่อ superclass reference ชี้ไปยัง subclass object ทำให้ การตัดสินใจว่าจะ execute method code ไหน จะเกิดขึ้นตอน runtime ซึ่งเหตุการณ์แบบนี้ เรียกว่า dynamic method binding หรือ late binding นั่นเอง

method ที่ทำ polymorphism ต้องเป็น method ที่เป็น virtual , abstract หรือเป็น method ของ interface เท่านั้น

Multiple Inheritance with Interface

Interface ต่างจาก abstract class อย่างไร ?

คำตอบก็คือชื่อหัวข้อครับ C# ไม่อนุญาติให้ทำ multiple inheritance กับclass แต่ interface ทำได้ครับ

 

 

11/10/44