在python中,如果你有一个类foo,你可以像这样为它创建一个自定义的添加函数:
class foo:
def __add__(self, other):
return stuff
这可以让您执行以下操作:
a = foo()
b = foo()
c = a + b
C#中的等价物是什么?
答案 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)
答案 3 :(得分:1)
您可以重载operator +
public static MyClass operator +(MyClass m1, MyClass m2)
{
// logic goes here
}