c# - "in"运算符和简单值传递 c# 之间的区别

标签 c#

根据 c# 7.2

The "in" operator Passes a variable in to a method by reference. Cannot be set inside the method.

我们可以这样写方法

 public static int Add(in int number1, in int number2)
 {
   return number1 + number2;
 }

并使用

调用它
 Add(ref myNo,4);

现在我的问题是,调用那个和这个之间的最大区别是什么**(有或没有“in”运算符)**

public static int Add(int number1, in int number2)
 {
   return number1 + number2;
 }

和调用一样

Add(3,4);

这段代码也做同样的事情

it could not be set if we want

,那么如果“in”和没有“in”之间的唯一区别是我们不能设置 inside 方法?或不。如果不是,请给我另一个例子。

最佳答案

下面清楚地解释了目的:

passes a variable in to a method by reference. Cannot be set inside the method.

From Official DOCS:

The in modifier on parameters, to specify that an argument is passed by reference but not modified by the called method.

唯一的区别是当参数有 in 运算符时,传入的参数值不能在方法中设置,而在普通参数中我们可以设置任何我们想要的值,使用 in 我们限制这样做。

例如:

 public static int Add(in int number1, in int number2)
 {
   number1 = 2; // this will give compile time error as we cannot set it.
   return number1 + number2;
 }

虽然在正常情况下我们可以随时设置,但在示例中设置没有意义但清楚地解释了区别:

 public static int Add(int number1,int number2)
 {
   number1 = 2; // this works.
   return number1 + number2;
 }

因此,我们可以说方法参数在技术上变得不可变。

您可以阅读有关它的更多详细信息here .

关于c# - "in"运算符和简单值传递 c# 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51875483/

相关文章:

c# - 你会如何限制每秒的操作次数?

c# - 从 MVC3 和 Razor 中的单个操作返回多个 View

c# - 通用策略模式

c# - Index was outside the bounds of the array 异常

c# - 从 PostMan 调用 asp.net 核心 web api

c# - 以编程方式从 PC 识别连接的设备是否为 Android

c# - 转换枚举?到整数?使用反射时失败

c# - 如何通过 photon unity network - unity 3d 实例化预制件来生成对象

c# - Assert.AreEqual 失败但不应该

c# - 绑定(bind)可空值时未设置值