2013-02-17 80 views
1
public static ListOfPeople operator +(ListOfPeople x, Person y) 
    { 
     ListOfPeople temp = new ListOfPeople(x); 
     if(!temp.PeopleList.Contains(y)) 
     { 
      temp.PeopleList.Add(y); 
     } 
     temp.SaveNeeded = true; 
     return temp; 
    } 

所以,我從來沒有使用運營商的過載功能,我試圖做的如何從我的課(人)對象添加到我的集合類(ListOfPeople)感。C#運算符重載使用

ListOfPeople包含一個屬性List<Person> PeopleList;

我的困難是如何得到這個方法的內部預先存在的列表添加一個新的人來。 ListOfPeople temp = new ListOfPeople(x);

我已經在這條線的錯誤,因爲我沒有構造函數一個ListOfPeople說法。如果我想使它成爲ListOfPeople temp = new ListOfPeople();那麼Temp就會調用我的默認構造函數,我只需創建一個新的空列表,並且不允許我將其添加到預先存在的列表中。

我只是不確定如何得到'臨時'來實際參考我的預存名單。

+1

你不應該使用+運算符將項目添加到集合。我相信這甚至作爲一個例子,運算符重載應該不被使用。 – antonijn 2013-02-17 17:01:08

+0

好吧,它將一個對象添加到Collection類中包含的List中。這仍然同樣糟糕嗎? – user1993843 2013-02-17 17:02:41

+1

是的,看看其他.NET列表如何實現添加項目,它總是通過「添加」方法。 – antonijn 2013-02-17 17:04:06

回答

1

使用方法如下:

public static ListOfPeople operator +(ListOfPeople x, Person y) 
{ 
    ListOfPeople temp = x; 
    if(!temp.PeopleList.Contains(y)) 
    { 
     temp.PeopleList.Add(y); 
    } 
    temp.SaveNeeded = true; 
    return temp; 
} 

public static ListOfPeople operator +(Person y, ListOfPeople x) 
{ 
    ListOfPeople temp = x; 
    if(!temp.PeopleList.Contains(y)) 
    { 
     temp.PeopleList.Add(y); 
    } 
    temp.SaveNeeded = true; 
    return temp; 
} 
  • 1日允許你使用:list = list + person
  • 第二個允許你使用:list = person + list

您可能還需要重載+=運營商(非-static),以便您可以使用list += person

編輯

雖然解決了我提到的問題。但是,那麼我同意其他人關於'+'的操作數是不可變的。

以下是更新現有的代碼(假設ListOfPeople.PeopleList is List<Person>):

public static ListOfPeople operator +(ListOfPeople x, Person y) 
{ 
    ListOfPeople temp = new ListOfPeople(); 
    temp.PeopleList.addRange(x); 
    if(!temp.PeopleList.Contains(y)) 
    { 
     temp.PeopleList.Add(y); 
    } 
    temp.SaveNeeded = true; 
    return temp; 
} 

public static ListOfPeople operator +(Person y, ListOfPeople x) 
{ 
    ListOfPeople temp = new ListOfPeople(); 
    temp.PeopleList.addRange(x); 
    if(!temp.PeopleList.Contains(y)) 
    { 
     temp.PeopleList.Add(y); 
    } 
    temp.SaveNeeded = true; 
    return temp; 
} 
+0

一旦你定義了+,我認爲+ =是隱含的? – 2013-02-17 17:08:45

+0

我的不好。是。 '+ ='解析爲'+'。 LH操作數取決於+ =的LHS。請參閱http://msdn.microsoft.com/en-us/library/sa7629ew.aspx – 2013-02-17 17:11:17

+3

我真的很想勸阻這樣的事情!它意味着沒有給出的東西!有了(a + b),我希望a會保持不變,我會得到一個新的結果。使用你的代碼,無論你是否指定值,列表都會改變。 – JustAnotherUserYouMayKnow 2013-02-17 17:22:52