简体   繁体   English

C#中的pred和succ等价于什么?

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

Pascal is my study language and I am curious whether C# also has the functions pred and succ . Pascal是我的学习语言,我很好奇C#是否还具有predsucc函数。

This is what I have done in Pascal that I want to try in C# 这就是我想在Pascal中尝试在C#中进行的操作

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

Is the same code applicable for C#, too? 同样的代码也适用于C#吗? If so, what is the namespace for these functions? 如果是这样,这些函数的名称空间是什么?

(I searched Google, but couldn't find the answer) (我搜索了Google,但找不到答案)

There aren't pred and succ functions in C#. C#中没有predsucc函数。 You just write n - 1 or n + 1 . 您只需写n - 1n + 1

You can use ++ or -- operator: 您可以使用++或-运算符:

3++ = 4
3-- = 2

Not sure why you would need it though when you can just do 3+1 or 3-1 :) 不知道为什么您只需要3 + 1或3-1时就需要它:)

You have method overloading in c# so it's easy to have pred and succ, You can do it by: 您在c#中具有方法重载,因此可以容易地进行pred和succ,可以通过以下方法实现:

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

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

Using extensions: 使用扩展名:

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

Then, this would work: 然后,这将起作用:

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

Probably not considered very idiomatic, but still works. 可能不是很习惯,但仍然可以。 Would have to override for other integer types (like short ). 必须覆盖其他整数类型(例如short )。 Check if the calls get inlined if you're concerned with performance. 如果您担心性能,请检查电话是否内联。

Note: ++ and -- act as Inc and Dec , not Succ and Pred . 注意: ++--充当IncDec ,而不是SuccPred

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM