C# 返回C中的字符串方法#
我试图用C# 返回C中的字符串方法#,c#,string,class,methods,return,C#,String,Class,Methods,Return,我试图用fullnamethod将SalesPerson对象中的字符串返回主程序,但这不起作用。我做错了什么 class SalesPerson { string firstName, lastName; public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set
fullnamethod
将SalesPerson
对象中的字符串返回主程序,但这不起作用。我做错了什么
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;
}
}
使用
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;
}
}
它要长得多,但当浏览一大块代码时,阅读起来要容易得多。这些答案都太复杂了
他写方法的方式很好。问题是他在哪里调用了这个方法。他在方法名后没有包含括号,因此编译器认为他试图从变量而不是方法中获取值
在Visual Basic和中,这些括号是可选的,但在C#中,它们是必需的。因此,要更正原始帖子的最后一行:
Console.WriteLine("{0}", x.fullNameMethod());
代码甚至都没有编译。您在控制台的行中出现语法错误。WriteLine。另一方面,
fullNameMethod
应该使用公共属性,而不是私有字段,并且在方法名称中使用单词method
有点,呃,冗余。看起来您对编程是新手。您不能访问这样的方法。让我看看我是否能用你的代码给出一个答案,但是重新格式化了properlyes,如果它是一个方法,用大括号调用它:Console.WriteLine(“{0}”,x.fullNameMethod())代码>是,这是我应该在Console.WriteLine(“{0}”,x.fullNameMethod())中执行的操作;感谢您打开Console.WriteLine(“{0}”,x.fullnamethod)
toConsole.WriteLine(“{0}”,x.fullNameMethod())代码>正是公认的答案所说的。