编译程序时出现以下错误:
错误1最佳重载方法匹配 ' System.Windows.Forms.ListBox.ObjectCollection.Add(对象)'有一些 无效参数C:\ Users \ Jose \ documents \ visual studio 2013 \ Projects \ practice1 \ practice1 \ Form1.cs 26 13 practice1
错误2参数1:无法转换为'方法组'至 '对象' C:\ Users \ Jose \ documents \ visual studio 2013 \ Projects \ practice1 \ practice1 \ Form1.cs 26 35 practice1
以下是我正在努力的代码:
namespace practice1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
talonary talonaryobj = new talonary(txtname.Text, txtlastname.Text,double.Parse(txtSalary.Text));
lsttalonary.Items.Add(talonaryobj.name);
lsttalonary.Items.Add(talonaryobj.lastname);
lsttalonary.Items.Add(talonaryobj.calculateSalary); //ERROR LINE
}
}
}
这是我正在使用的课程:
namespace practice1
{
public class talonary
{
public string name;
public string lastname;
public double salary;
public talonary(string n, string ln, double s)
{
this.name = n;
this.lastname = ln;
this.salary = s;
}
public string calculateSalary(double s)
{
s = s - (s * 0.05);
return s.ToString();
}
}
}
答案 0 :(得分:2)
您需要将参数传递给calculateSalary
方法。当您使用不带参数的方法名称时,您将方法本身传递给Add
方法,而不是调用方法并获得结果。
此
lsttalonary.Items.Add(talonaryobj.calculateSalary); //ERROR LINE
应该是:
lsttalonary.Items.Add(talonaryobj.calculateSalary(talonaryobj.salary)); //Fixed line :)
最好不要将薪水传递给calculateSalary
方法。为什么不这样:
public string CalculateSalary()
{
var s = this.salary - (this.salary * 0.05);
return s.ToString();
}
然后你可以这样称呼它:
lsttalonary.Items.Add(talonaryobj.CalculateSalary());
答案 1 :(得分:0)
行lsttalonary.Items.Add(talonaryobj.calculateSalary(double s));
调用一个方法(calculateSalary),该方法在double s
的参数中传递。您没有给它double
执行计算。它看起来应该返回与薪水相关的东西,所以也许你想要lsttalonary.Items.Add(talonaryobj.calculateSalary(talonaryobj.salary));
答案 2 :(得分:0)
如另一个答案所述,您没有将值传递给CalculateSalary
函数。我会更进一步说它应该是Salary
类型的double
属性。
private double salary;
public double Salary { get { return salary; } }
然后你的代码应该处理在类之外格式化薪水值。
我还建议在属性中包装字段(可能是只读的)。
private string name;
private string lastname;
public string Name { get { return name; } }
public string Lastname { get { return lastname; } }
然后你需要修改你的主叫代码。
private void button1_Click(object sender, EventArgs e)
{
talonary talonaryobj = new talonary(txtname.Text, txtlastname.Text,double.Parse(txtSalary.Text));
lsttalonary.Items.Add(talonaryobj.Name);
lsttalonary.Items.Add(talonaryobj.Lastname);
//lsttalonary.Items.Add(talonaryobj.calculateSalary); //ERROR LINE
lsttalonary.Items.Add(string.Format("##some format string here##", talonaryobj.Salary));
}