关于C#中继承和接口
接口也是一种类型,和委托类似。可以有自己的实例。
同时,在继承中,有一个很重要的概念:里氏转换。
里氏转换有两个重要概念:
1.子类可以赋值给父类。
2.包含子类的父类对象可以强制转换成子类。
窗体布局如图所示,代码如下:
namespace 接口练习
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 声明一个接口,用于定义speak方法,而speak的具体功能实现是在类中进行的
/// </summary>
interface ISelectLanguage
{
void Speak(string str);
}
class C_SpeakChinese : ISelectLanguage
{
public void Speak(string str)
{
MessageBox.Show("您对中国友人说:" + str, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
class C_SpeakEnglish : ISelectLanguage
{
public void Speak(string str)
{
MessageBox.Show("您对美国友人说:" + str, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.SelectedIndex = 0;
}
public bool CheckChinese(string str)
{
bool flag = false;
UnicodeEncoding a = new UnicodeEncoding();
byte[] b = a.GetBytes(str);
for (int i = 0; i < b.Length; i++)
{
i++;
if (b[i] != 0)
{
flag = true;
}
else
{
flag = false;
}
}
return flag;
}
private void button1_Click(object sender, EventArgs e)
{
if (txtContent.Text == "")
{
MessageBox.Show("不想跟友人说点什么吗?", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
if (comboBox1.SelectedIndex == 0)//与中国人对话
{
if (CheckChinese(txtContent.Text))
{
ISelectLanguage Interface1 = new C_SpeakChinese();
Interface1.Speak(txtContent.Text);
}
else
{
MessageBox.Show("请和中国友人说汉语?", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else//与美国人对话
{
if (CheckChinese(txtContent.Text))
{
MessageBox.Show("请和美国友人说英语?", "警告", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
ISelectLanguage Interface1 = new C_SpeakEnglish(); //父类可以new 子类对象?
Interface1.Speak(txtContent.Text);
}
}
}
}
}
}