C#返回一个字符串方法
我想从SalesPerson
对象fullNameMethod
返回一个字符串到主程序,但这是行不通的。我究竟做错了什么?C#返回一个字符串方法
class SalesPerson
{
string firstName, lastName;
public string FirstName { get { return firstName; } set { firstName = value; } }
public string LastName { get { return lastName; } set { lastName = value; } }
public SalesPerson(string fName, string lName)
{
firstName = fName;
lastName = lName;
}
public string fullNameMethod()
{
string x = firstName + " " + lastName;
return x;
}
}
class Program
{
static void Main(string[] args)
{
SalesPerson x = new SalesPerson("john", "Doe");
Console.WriteLine("{0}",x.fullNameMethod);
}
}
你目前正试图访问像属性的方法
Console.WriteLine("{0}",x.fullNameMethod);
应该
Console.WriteLine("{0}",x.fullNameMethod());
或者你可以把它变成使用
public string fullName
{
get
{
string x = firstName + " " + lastName;
return x;
}
}
是的,这是我应该做的Console.WriteLine(“{0}”,x。fullNameMethod()); 非常感谢 – user1462498
使用proprty x.fullNameMethod()
调用方法
你不必有专门的方法,你可以创建一个属性是这样,而不是:
class SalesPerson
{
string firstName, lastName;
public string FirstName { get { return firstName; } set { firstName = value; } }
public string LastName { get { return lastName; } set { lastName = value; } }
public string FullName { get { return this.FirstName + " " + this.LastName; } }
}
类甚至可以缩短为:
class SalesPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName {
get { return this.FirstName + " " + this.LastName; }
}
}
然后
属性可以像任何其他属性访问:
class Program
{
static void Main(string[] args)
{
SalesPerson x = new SalesPerson("John", "Doe");
Console.WriteLine(x.FullName); // Will print John Doe
}
}
你忘了()结尾。它不是一个变量,而是一个函数,当没有参数时,你仍然需要()在末尾
对于未来的编码实践,我强烈建议稍微改造一下代码,这可能会令人沮丧地阅读:
public string LastName
{ get { return lastName; } set { lastName = value; } }
如果在这里发生任何类型的处理,谢天谢地不会发生在这里,它会变得非常混乱。如果你要通过你的代码到别人,我会建议:
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
它长得多的时间,但它更容易在代码巨大部分一眼时阅读。
这些答案都太复杂了!他写这个方法的方式很好。问题在于他调用了该方法。他没有在方法名后加括号,所以编译器认为他试图从变量而不是方法中获取值。 在VB和Delphi中,这些括号是可选的,但在C#中,它们是必需的。 因此,要更正原始帖子的最后一行,请输入: Console.WriteLine(“{0}”,x.fullNameMethod());
什么不起作用? – CodeZombie
代码甚至没有编译。用'Console.WriteLine'命令行有语法错误。 – Oded
给我们提供错误信息。虽然它可能沿着x.fullNameMethod不存在的路线。 –