Pascal 是我的学习语言,我很好奇C#是否也有函数pred和succ.
这就是我在 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#?如果是这样,这些函数的命名空间是什么?
(我搜索了谷歌,但找不到答案)
Pascal 是我的学习语言,我很好奇C#是否也有函数pred和succ.
这就是我在 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#?如果是这样,这些函数的命名空间是什么?
(我搜索了谷歌,但找不到答案)
C#中没有pred和succ函数。你只写n - 1or n + 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)。如果您关心性能,请检查调用是否内联。
注意:++and--充当Incand Dec,而不是Succand Pred。
您可以使用 ++ 或 -- 运算符:
3++ = 4
3-- = 2
不知道为什么当你可以做 3+1 或 3-1 时你会需要它:)