2011-05-25 270 views
4

有沒有辦法將參數傳遞給setter? 我如何將一個字符串傳遞給setter? 我如何使用新字符串param調用setter?有沒有辦法將參數傳遞給setter

public string It 
{ 
    get{ { return it;} 

    set { it = value;} 
} 

非常感謝您

回答

4

您可以將它一樣可以賦值給變量:

It = "My String"; 

屬性getter/setter方法是string get_It()void set_It(string value)

只是語法糖
10

根據您分配給屬性的值,setter獲取value作爲其自己的「參數」:

foo.It = "xyz"; // Within the setter, the "value" variable will be "xyz" 

如果你想使用一個額外的參數,你需要一個索引

public string this[string key] 
{ 
    get { /* Use key here */ } 

    set { /* Use key and value here */ } 
} 

那麼你訪問它

foo["key"] = "newValue"; 

你不能給索引C#中的名稱,或者按名稱使用其他語言的命名索引器(C#4以外的COM除外)。編輯:正如Colin所指出的那樣,您應該仔細使用索引器......不要僅僅將它們用作獲取額外參數的一種方法,例如,在setter中,然後忽略getter中的參數。這樣的事情將是可怕的:

// Bad code! Do not use! 
private string fullName; 
public string this[string firstName] 
{ 
    get { return fullName; } 
    set { fullName = firstName + " " + value; } 
} 

// Sample usage... 
foo["Jon"] = "Skeet"; 
string name = foo["Bar"]; // name is now "Jon Skeet" 
+1

只是爲了補充一點。除非你正在設置的東西有某種可索引語義,否則不要使用索引器,因爲任何維護代碼的人都會懷疑地球究竟會發生什麼。 – 2011-05-25 12:35:44

+0

不應該是返回fullName;在getter而不是返回firstName;因爲它返回「Jon Skeet」,當前的代碼肯定會返回「Bar」? – 2011-05-26 09:20:32

+0

@John:是的,就是這個意圖。衛生署!固定。 – 2011-05-26 09:22:49

0

一般來說,對於任何財產,直接就可以賦值即It = "";

1

這就是C#性能的基礎知識:

Properties (C# Programming Guide)

假設你創建了一個具有該屬性的對象等值線:

Blah blah = new Blah(); 
blah.It = "Hello World"; 
String hey = blah.It; 

屬性的想法是用一些更多的邏輯(和一些隱藏)來調用局部變量。所以語法類似於使用本地類變量

2

屬性在C#中不允許參數。

如果你真的需要,以SE It aditional的信息正確,則推薦的解決方案是實現二傳手的方法:

public void SetIt(string value, string moreInfo) {...} 
0

恭維別人都在這個年齡線程說...

也許更好的方法是定義一個struct來保存想要傳遞的額外信息,然後以這種方式傳遞數據。例如:

struct PersonName { 

    public string Forename { get; set; } 
    public string Surname { get; set; } 

    public PersonName(string fn, string sn) { 
     Forename = fn; 
     Surname = sn; 
    } 

} 

class MyPerson { 

    public string Forename { get; set; } 
    public string Surname { get; set; } 
    public DateTime dob { get; set; } 

    ... 

    public PersonName Fullname { 
     get { return Forename + " " + Surname; } 
     set { 
      Forename = value.Forename; 
      Surname = value.Surname; 
     } 
    } 
} 

... 

    public void main() { 
     MyPerson aPerson = new MyPerson; 
     aPerson.Fullname = new PersonName("Fred", "Bloggs"); 
    } 

雖然我個人認爲這對於如此輕微的事情來說是過度的。此外,它然後乞討的問題 - 爲什麼不Forename,Surname對已被定義爲適當的structPersonName)?

相關問題