C#的新手想知道是否存在从方法中调用对象的方法
我是否必须继续输入
Console.WriteLine(James.name); Console.WrtieLine(James.age);
对于我制作的每个新对象?
很抱歉,如果这是一个简单的问题。:(
例:
https://i.stack.imgur.com/6GVXV.png
命名空间示例{
class Dog
{
public string name;
public int age;
public Dog(string _name, int _age)
{
name = _name;
age = _age;
}
}
class Program
{
public static void Main()
{
Dog James = new Dog("James", 4);
Dog Daniel = new Dog("Daniel", 2);
}
//I know from thispart it does not work but is there a way to make a similar result?
status(James);
status(Daniel);
}
public static void status(thisdog)
{
Console.WriteLine(thisdog.name);
Console.WrtieLine(thisdog.age);
}
您的代码应该可以正常工作,您只需要修复一些错误(内联注释):
class Program
{
public static void Main()
{
Dog James = new Dog("James", 4);
Dog Daniel = new Dog("Daniel", 2);
status(James); // <-- This needs to be inside Main
status(Daniel);
}
// This needs a type for the parameter and needs to be inside Program
public static void status(Dog thisdog)
{
Console.WriteLine(thisdog.name);
Console.WriteLine(thisdog.age); // <-- fixed typo
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句