簡體   English   中英

C#中的pred和succ等價於什么?

[英]What's the equivalent for pred and succ in C#?

Pascal是我的學習語言,我很好奇C#是否還具有predsucc函數。

這就是我想在Pascal中嘗試在C#中進行的操作

// in Pascal:
pred(3) = 2
succ(False) = True
pred('b') = 'a'
type enum = (foo, bar, baz);
succ(bar) = baz; pred(bar) = foo

同樣的代碼也適用於C#嗎? 如果是這樣,這些函數的名稱空間是什么?

(我搜索了Google,但找不到答案)

C#中沒有predsucc函數。 您只需寫n - 1n + 1

您可以使用++或-運算符:

3++ = 4
3-- = 2

不知道為什么您只需要3 + 1或3-1時就需要它:)

您在c#中具有方法重載,因此可以容易地進行pred和succ,可以通過以下方法實現:

public int pred(int input)
{
   return input - 1;
}

public char pred(char input)
{
  return (char)((int)input - 1);
}
....

使用擴展名:

public static int Pred(this int self) => self - 1;
public static int Succ(this int self) => self + 1;

然后,這將起作用:

3.Pred() //-> 2
int x = 3;
x.Succ() //-> 4

可能不是很習慣,但仍然可以。 必須覆蓋其他整數類型(例如short )。 如果您擔心性能,請檢查電話是否內聯。

注意: ++--充當IncDec ,而不是SuccPred

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM