2012-07-06 22 views
1

如果您在屬性上獲得i ++類型的操作,是否存在可以添加的特殊方法?如何在c語言的set語句中使用i ++操作符

這是我想要做的一個例子。我知道這是行不通的,但這讓你知道我在說什麼。實際上,我正在與兩個內部工作,我想增加一個+和另一個 - 。

int mynum; 
int yournum 
{ 
    get{ return mynum; } 
    set{ mynum = value; } 
    set++{ mynum = mynum + 5; return mynum; } //this is what I want to do 
} 
// elsewhere in the program 
yournum++; //increases by 5 
+0

你能解釋一下嗎?我不明白你在問什麼。 – 2012-07-06 17:05:26

回答

5

聽起來好像要覆蓋時++是對房地產yournum調用時發生的行爲。如果是這樣,在C#中不可能完全代表您在示例中列出的代碼。 ++運營商應增加1,並且每個調用yournum++的用戶都會預期該行爲。要以靜默方式更改爲5肯定會導致用戶混淆

這將有可能通過定義一個定製++算子做了+ 5轉換,而不是+1類型得到類似的行爲。例如

public struct StrangeInt 
{ 
    int m_value; 

    public StrangeInt(int value) 
    { 
     m_value = value; 
    } 

    public static implicit operator StrangeInt(int i) 
    { 
     return new StrangeInt(i); 
    } 

    public static implicit operator int(StrangeInt si) 
    { 
     return si.m_value; 
    } 

    public static StrangeInt operator++(StrangeInt si) 
    { 
     return si.m_value + 5; 
    } 
} 

如果你現在定義yournameStrangeInt,那麼你會得到你要找的

+0

如何重載結構的get(所以我可以處理返回值)?這實際上是我正在處理的問題的一部分,儘管當我編寫示例並沒有時間包含所有內容時我很匆忙。另外,操作員必須是靜態的嗎?或者有這樣的理由嗎? – 2012-07-06 17:49:54

+0

@ArlenBeiler我不太清楚「超負荷」的含義。如果你試圖重載屬性'get'在給定的類型上工作是不可能的。至於運營商是的,他們必須是靜態的。至於爲什麼這就是C#如何定義它們。可能存在一致性問題。 – JaredPar 2012-07-06 17:51:20

+0

非常感謝。這是我的最終代碼:http://stackoverflow.com/a/11367723/258482而且讓操作符靜態是有意義的。 :) – 2012-07-06 18:28:14

1

是的,但(總是但是)行爲...物業類型不能爲int,您需要返回一個自定義代理類型,該類型隱式轉換爲int,但覆蓋運算符。

1

沒有辦法直接做到這一點。提供此方法的一種方法(如果您真的需要它),將提供您自己的類型而不是int並使用operator overloading來實現您所需的功能。

1

如果你想覆蓋整數運算符++那麼這不會是不幸的。

1

創建自己的結構和重載操作:使用基本類型

public static YourType operator++(YourType t) 
    { 
      // increment some properties of t here 
      return t; 
    } 
0

不可能的。我會做的,而不是爲添加擴展的方法來詮釋 - 是這樣的:

public static int plusFive(this int myInt) 
{ 
    return myInt + 5; 
} 

然後,使用它,你可以這樣做:

int a,b; 
a = 5; 
b = a.plusFive(); 
1

非常感謝JaredPar爲his excellent answer 。如果有人感興趣,這是最終的結果。它是計算一個基於兩個數字的百分比,以便隨着更多數字的增加而增加重量(因此得名)。

public struct Weight 
{ 
    int posWeight; 
    int negWeight; 
    int Weight 
    { 
     get 
     { 
      if (posWeight + negWeight == 0) //prevent div by 0 
       return 0; 
      else return posWeight/(posWeight + negWeight); 
     } 
    } 
    public static Weight operator ++(Weight num) 
    { 
     num.posWeight++; 
     if (num.posWeight > 2000000) //prevent integer overflow 
     { 
      num.posWeight = num.posWeight/2; 
      num.negWeight = num.negWeight/2; 
     } 
     return num; 
    } 
    public static Weight operator --(Weight num) 
    { 
     num.negWeight++; 
     if (num.negWeight > 2000000) //prevent integer overflow 
     { 
      num.posWeight = num.posWeight/2; 
      num.negWeight = num.negWeight/2; 
     } 
     return num; 
    } 
    public static explicit operator int(Weight num) 
    { // I'll make this explicit to prevent any problems. 
     return num.Weight; 
    } 
}