如何在C#中为类创建自定义添加方法

时间:2015-08-24 13:28:50

标签: c# function add

在python中,如果你有一个类foo,你可以像这样为它创建一个自定义的添加函数:

class foo:
    def __add__(self, other):
        return stuff

这可以让您执行以下操作:

a = foo()
b = foo()
c = a + b

C#中的等价物是什么?

4 个答案:

答案 0 :(得分:7)

您可以为示例实现operator

public class Foo
{
   public static Foo operator +(Foo f1, Foo f2) 
   {
      var foo = // some logic to generate a result
      return foo;
   }
}

然后您可以尝试使用此运算符:

var a = new Foo() { /* properties initialization */ };
var b = new Foo() { /* properties initialization */ };

var c = a + b;

您可以实施更多运算符,例如-*\|&,就像上面的示例一样。

查看更多内容 https://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx

答案 1 :(得分:3)

此功能称为运算符重载。

您可以在此处阅读:https://msdn.microsoft.com/en-us/library/aa288467%28v=vs.71%29.aspx

简短的例子:

public static  void Send(XBeeAddress64 destination, int[] payload) throws XBeeException{

      int errors = 0;        int ackErrors = 0;         int ccaErrors = 0;        int purgeErrors = 0;        long now; 

      TxRequest64 tx = new TxRequest64(destination,payload); 

      now = System.currentTimeMillis();
      FindEndDevice.cordinnator.sendAsynchronous(tx);
      XBeeResponse response = null;
      while (true) {    
          System.out.println("***************************J'envoi les données to End Device ******************");
          // blocks until we get response
      response = FindEndDevice.cordinnator.getResponse();
      if (response.getApiId() != ApiId.TX_STATUS_RESPONSE) {
          log.debug("*** expected tx status but received " + response);
      } else {
          if (((TxStatusResponse) response).getFrameId() != tx.getFrameId()) {
              throw new RuntimeException("**** frame id does not match");
          }
          if (((TxStatusResponse) response).getStatus() != TxStatusResponse.Status.SUCCESS) {
              errors++;
              if (((TxStatusResponse) response).isAckError()) {
                    ackErrors++;
              } else if (((TxStatusResponse) response).isCcaError()) {
                      ccaErrors++;
              } else if (((TxStatusResponse) response).isPurged()) {
                      purgeErrors++;
              }
              log.debug("*** Tx status failure with status: " + ((TxStatusResponse) response).getStatus());
          } else {
              // success
               log.debug("*** Success Envoi. errors is " + errors + ", in " + (System.currentTimeMillis() - now) + ", ack errors "
                                          + ackErrors + ", ccaErrors " + ccaErrors + ", purge errors " + purgeErrors);
          }
          break;
      }
      }//fin while
      System.out.println("**** Fin Send********");
}

答案 2 :(得分:2)

您正在寻找的是"运营商重载"。请看一下本教程:

Operator Overloading Tutorial

这教你如何使用正确的语法为类foo的对象编写+运算符的特定功能。

答案 3 :(得分:1)

您可以重载operator +

public static MyClass operator +(MyClass m1, MyClass m2) 
{
    // logic goes here
}