我不明白构造函数是如何工作的。我试图将这些数字带入课程的主程序中,但每当我尝试在主程序上使用construtor时,它就会出现" Class Fooditem不包含一个带有2个参数的构造函数#34 ;.这非常混乱,因为我有一个叫public food(string name, int numberserved)
的权利。我不明白为什么会出现这条消息而且我不知道如何修复它。任何帮助,将不胜感激。
class Program
{
static void Main(string[] args)
{
FoodItem firstfood = new FoodItem("Spagetti", 3);
Console.WriteLine("The First Food is '{0}' And it serves {1}", firstfood.Name, firstfood.NumberServed);
}
}
class FoodItem
{
string _name;
int _numberserved;
public void food(string name)
{
_name = name;
_numberserved = 0;
}
public void food(string name, int numberserved)
{
_name = name;
NumberServed = numberserved;
}
public string Name
{
get
{
return _name;
}
}
public int NumberServed
{
get
{
return _numberserved;
}
set
{
if (value > 4)
{
_numberserved = 4;
}
else
{
_numberserved = value;
}
}
}
}
答案 0 :(得分:3)
构造函数应该与您的类具有相同的名称,并且没有返回类型:
class FoodItem
{
string _name;
int _numberserved;
public FoodItem(string name)
{
_name = name;
_numberserved = 0;
}
public FoodItem(string name, int numberserved)
{
_name = name;
NumberServed = numberserved;
}
}
答案 1 :(得分:1)
如果该类被调用FoodItem
,那么构造函数也应该被称为FoodItem
并且没有返回值:
public class FoodItem
{
public FoodItem()
{
// Do stuff
}
public FoodItem(string name, int numberserved)
{
// Do stuff
}
}
您可以使用: this
构造将构造函数链接在一起。它可以以任何方式工作:
public FoodItem()
{
// Do basic stuff
}
public FoodItem(string name, int numberserved) : this()
{
// Do other stuff
}
或
public FoodItem() : this ("defaultName", 0)
{
}
您的所作所为完全取决于您的申请。
答案 2 :(得分:0)
您错误地命名了构造函数。将其更改为FoodItem,如下所示:
$.each($footerObj, function(key, value) {
$('.footer__links').append('<ul class="footer__list"></ul>');
var $footerList = $('.footer__list');
$.each(value.links, function(subkey, subvalue) {
$footerList.append('<li class="footer__item"><a class="footer__link" href="' + subvalue.url + '">' + subvalue.title + '</a></li>');
});
});
答案 3 :(得分:0)
我已更改了您的代码,现在可以使用了。
class Program
{
static void Main(string[] args)
{
FoodItem firstfood = new FoodItem("Spagetti", 3);
Console.WriteLine("The First Food is '{0}' And it serves {1}", firstfood.Name, firstfood.NumberServed);
}
}
class FoodItem
{
string _name;
int _numberserved;
public void food(string name)
public FoodItem()
{
_name = name;
_numberserved = 0;
}
public void food(string name, int numberserved)
public FoodItem(string name, int numberserved)
{
_name = name;
NumberServed = numberserved;
}
public string Name
{
get
{
return _name;
}
}
public int NumberServed
{
get
{
return _numberserved;
}
set
{
if (value > 4)
{
_numberserved = 4;
}
else
{
_numberserved = value;
}
}
}
}
请告诉我您的想法或反馈。
感谢 KARTHIK