【发布时间】:2014-05-07 00:10:23
【问题描述】:
今天我遇到了 C# 接口的概念,我希望有一个简单的问题,看看我是否理解它们……它们与 C++ 头文件非常相似吗?我的意思是,从我得到的信息来看,你定义了一个类的主干而没有真正定义它的作用,这有点类似于标题,对吗?我阅读了整个 MSDN 定义,但它并没有真正让我 100% 清楚。我相信我有这个想法(编写并附加了一个非常基本的程序,看看我是否理解)但我至少在明天晚上之前完全理解它们的基础知识是非常重要的。
示例:
namespace InterfaceTest
{
class Program
{
static void Main(string[] args)
{
KitchenStaff newKitchen = new KitchenStaff();
newKitchen.getBakers();
newKitchen.getBaristas();
newKitchen.getCooks();
Console.ReadLine();
KitchenDuties newKitchen1 = new KitchenDuties();
newKitchen1.getBakers();
newKitchen1.getBaristas();
newKitchen1.getCooks();
Console.ReadLine();
}
}
interface Bakers
{
void getBakers();
}
interface Cooks
{
void getCooks();
}
interface Baristas
{
void getBaristas();
}
class KitchenInfo
{
private string m_kitchen_name = "";
private Int16 m_bakers = 0;
private Int16 m_baristas = 0;
private Int16 m_cooks = 0;
public string Name
{
get
{
return m_kitchen_name.ToString();
}
set
{
m_kitchen_name = value;
}
}
public string Bakers
{
get
{
return m_bakers.ToString();
}
set
{
m_bakers = Convert.ToInt16(value);
}
}
public string Baristas
{
get
{
return m_baristas.ToString();
}
set
{
if (value != string.Empty)
{
m_baristas = Convert.ToInt16(value);
}
}
}
public string Cooks
{
get
{
return m_cooks.ToString();
}
set
{
if (value != string.Empty)
{
m_cooks = Convert.ToInt16(value);
}
}
}
}
class KitchenStaff : KitchenInfo, Bakers, Cooks, Baristas
{
public KitchenStaff()
{
Console.WriteLine("What is this kitchens name?");
Name = Console.ReadLine();
Console.WriteLine("How many bakers?");
Bakers = Console.ReadLine();
Console.WriteLine("How many baristas?");
Baristas = Console.ReadLine();
Console.WriteLine("How many cooks?");
Cooks = Console.ReadLine();
}
public void getBakers()
{
System.Console.WriteLine("In {0} there are {1} bakers.", Name, Bakers);
}
public void getBaristas()
{
System.Console.WriteLine("In {0} there are {1} baristas.", Name, Baristas);
}
public void getCooks()
{
System.Console.WriteLine("In {0} there are {1} cooks.", Name, Cooks);
}
}
class KitchenDuties : KitchenInfo, Bakers, Cooks, Baristas
{
public KitchenDuties()
{
Console.WriteLine("What is this kitchens name?");
Name = Console.ReadLine();
Console.WriteLine("How many bakers?");
Bakers = Console.ReadLine();
Console.WriteLine("How many baristas?");
Baristas = Console.ReadLine();
Console.WriteLine("How many cooks?");
Cooks = Console.ReadLine();
}
public void getBakers()
{
System.Console.WriteLine("In {0}, the {1} bakers make fattening cookies.", Name, Bakers);
}
public void getBaristas()
{
System.Console.WriteLine("In {0}, the {1} baristas serve hot coffee.", Name, Baristas);
}
public void getCooks()
{
System.Console.WriteLine("In {0}, the {1} cooks make tender steak.", Name, Cooks);
}
}
}
【问题讨论】:
-
C# 接口映射到 C++ 抽象类
-
仅当抽象类是纯虚拟的。
标签: c# c++ inheritance interface