接口如何知道调用哪个类方法?这是正确的代码吗?或者不是
namespace IntExample
{
interface Iinterface
{
void add();
void sub();
}
public partial class Form1 : Form,Iinterface
{
public Form1()
{
InitializeComponent();
}
public void add()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a + b;
txtresult.Text = c.ToString();
}
public void sub()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a - b;
txtresult.Text = c.ToString();
}
private void btnadd_Click(object sender, EventArgs e)
{
add();
}
private void button2_Click(object sender, EventArgs e)
{
sub();
}
class cl2 : Form1,Iinterface
{
public void add()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a + b;
txtresult.Text = c.ToString();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}发布于 2012-12-12 17:48:19
接口不“知道”要调用哪个类方法。它只是定义了可用的方法。
由于cl2没有实现sub方法,所以您发布的代码不会进行编译,但这几乎没有任何意义。
我不知道你在尝试做什么,所以我将举一个例子来说明接口的有效用法。
您可以有几个实现该接口的表单,然后在您的主表单中,您可以根据索引或名称选择要显示的表单。
因此,要存储所有表单,您可以使用泛型列表:
List<Iinterface> forms = new List<Iinterface>();将实现该接口的所有窗体添加到列表中:
forms.Add(new Form1());
forms.Add(new Form2());
forms.Add(new Form3());
//...然后,您可以显示特定的表单并从接口调用方法:
//find by index:
forms[index].Show();
forms[index].add();
//find by name:
string name="form 2";
Iinterface form = forms.Find(f => f.Name == name);
if (form != null)
{
form.Show();
form.add();
}https://stackoverflow.com/questions/13836802
复制相似问题