2012-07-06 18 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; 
    } 
}