1. 程式人生 > 程式設計 >c# 介面使用例項

c# 介面使用例項

用介面實現一個簡單的物件的入庫,出庫

如定義一個物流類介面,包含物件所屬快遞公司名稱屬性,物件單號屬性及資訊顯示方法。通過物件出庫類資訊和物件入庫類資訊繼承該介面。

文件介面如下:

c# 介面使用例項

如下:

(一)介面定義

//定義一個介面IMyinterface
    interface IMyinterface {

      void commodityInformation();//定義一個快遞資訊顯示方法
      string Id { get; set; }//定義一個快遞單號屬性
      string Name { get; set; }///定義一個快遞所屬快遞公司名稱屬性
    }

(二)物件入庫類

//入庫類
    public class Inbound : IMyinterface
    {

      string id = "";
      string name = "";

      public string Id {

        get { return id; }
        set { id = value; }
      }
      public string Name {

        get { return name; }
        set { name = value; }
      }
      void IMyinterface.CommodityInformation()
      {

        Console.WriteLine("入庫資訊:\n" + "物件單號:" + Id + " " + "所屬快遞公司:" + Name);
      }
    }

(三)物件出庫類

//出庫類
    public class Outbound : IMyinterface {

      string id = "";
      string name = "";

      public string Id {

        get { return id; }
        set { id = value; }
      }

      public string Name {

        get { return name; }
        set { name = value; }
      }

      void IMyinterface.CommodityInformation() {

        Console.WriteLine("出庫資訊:\n" + "物件單號:" + Id + " " + "所屬快遞公司:" + Name);
      }
    }

(四)呼叫介面,實現結果

1,所先要引用ConsoleApp2如下

c# 介面使用例項

2,呼叫介面:

static void Main(string[] args)
    {
      IMyinterface[] face = { new Inbound(),new Outbound() };
      face[0].Id = "X78945612355";
      face[0].Name = "申通";
      face[0].CommodityInformation();

      face[1].Id = "X78912345674";
      face[1].Name = "順豐";
      face[1].CommodityInformation();
      Console.ReadKey();
    }

3,實現結果如下:

c# 介面使用例項

以上就是c# 介面使用例項的詳細內容,更多關於c# 介面使用的資料請關注我們其它相關文章!