2012-07-03 164 views
-3

我想從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); 
    } 
} 
+2

什麼不起作用? – CodeZombie

+1

代碼甚至沒有編譯。用'Console.WriteLine'命令行有語法錯誤。 – Oded

+0

給我們提供錯誤信息。雖然它可能沿着x.fullNameMethod不存在的路線。 –

回答

9

你目前正試圖訪問像屬性的方法

Console.WriteLine("{0}",x.fullNameMethod); 

應該

Console.WriteLine("{0}",x.fullNameMethod()); 

或者你可以把它變成使用

public string fullName 
{ 
    get 
    { 
     string x = firstName + " " + lastName; 
     return x; 
    } 
} 
+1

是的,這是我應該做的Console.WriteLine(「{0}」,x。fullNameMethod()); 非常感謝 – user1462498

0

使用proprty x.fullNameMethod()調用方法

0

你不必有專門的方法,你可以創建一個屬性是這樣,而不是:

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 
    } 
} 
0

你忘了()結尾。它不是一個變量,而是一個函數,當沒有參數時,你仍然需要()在末尾

對於未來的編碼實踐,我強烈建議稍微改造一下代碼,這可能會令人沮喪地閱讀:

public string LastName 
{ get { return lastName; } set { lastName = value; } } 

如果在這裏發生任何類型的處理,謝天謝地不會發生在這裏,它會變得非常混亂。如果你要通過你的代碼到別人,我會建議:

public string LastName 
{ 
    get 
    { 
    return lastName; 
    } 
    set 
    { 
    lastName = value; 
    } 
} 

它長得多的時間,但它更容易在代碼巨大部分一眼時閱讀。

-2

這些答案都太複雜了!他寫這個方法的方式很好。問題在於他調用了該方法。他沒有在方法名後加括號,所以編譯器認爲他試圖從變量而不是方法中獲取值。 在VB和Delphi中,這些括號是可選的,但在C#中,它們是必需的。 因此,要更正原始帖子的最後一行,請輸入: Console.WriteLine(「{0}」,x.fullNameMethod());