2012-10-17 16 views
1

我新的ASP.NET &試圖創建一個對象,但有一個語法錯誤創建一組獲得類和傳遞參數的構造函數

public class pair 
{ 

    private string key; 
    private string value; 

    public pair(string key, string value) 
    { 
     this.key = this.setKey(key); 
     this.value = this.setValue(value); 
    } 

    private void setKey (string key) { 
     this.key = key; 
    } 

    public string getKey() 
    { 
     return this.key; 
    } 

    private void setValue(string value) 
    { 
     this.value = value; 
    } 

    public string getValue() 
    { 
     return this.value; 
    } 

} 

這兩條線

this.key = this.setKey(key); 
this.value = this.setValue(value); 

有有什麼不對,有誰知道這些問題?

+0

問題固定... – hkguile

+0

爲什麼你那麼問..?@ hkinterview –

+0

你分配不具有返回值(空)的方法的返回值。您應該更多地關注編譯器的錯誤消息。 – VahidNaderi

回答

6

你只需要兩個屬性在這裏或只是使用

public class Pair 
{ 
    public string Key { get; private set; } 
    public string Value { get; private set; } 

    public Pair(string key, string value) 
    { 
     this.Key= key; 
     this.Value = value; 
    } 
} 
+1

設置者應該在這裏私人模仿原始代碼。我也將它改爲'Pair',但這是一個單獨的問題... –

+0

謝謝@JonSkeet –

0

你不需要使用的方法,只是構造函數的參數:

public class pair 
{ 

    private string key; 
    private string value; 

    public pair(string key, string value) 
    { 
     this.key = key; 
     this.value = value; 
    } 

    private string Key 
    { 
     get { return key; } 
     set { key = value; } 
    } 

    public string Value 
    { 
     get { return this.value; } 
     set { this.value = value; } 
    } 
} 
+0

請注意,爲平凡的屬性編寫明確的getter和setter是不必要的冗長,因爲C#3引入了自動實現的屬性。 –

3

你並不需要創建自己的類,.NET支持2個類似這樣的內置類。因此,您可以使用KeyValuePair<string, string>Tuple<string, string>代替

1

每個人都提供了一個修復程序,但沒有人回答實際問題。問題在於,作業的右側是void方法,但它需要具有與作業類型相同的類型或可隱式轉換爲作業類型的類型。由於string是密封的,在這種情況下,表達式的右側必須是字符串表達式。

string M1() { return "Something"; } 
object M2() { return new object(); } 
void M3() { } 

string s = "Something"; //legal; right side's type is string 
string t = M1(); //legal; right side's type is string 
string u = M2(); //compiler error; right side's type is object 
string v = M2().ToString(); //legal; right side's type is string 
string w = (string)M2(); //compiles, but fails at runtime; right side's type is string 
string x = M3(); //compiler error; right side's type is void 
相關問題