前几天有人问我他们什么时候应该使用参数关键字out而不是ref。虽然我(我认为)理解ref和out关键字之间的区别(之前已经问过了),最好的解释似乎是ref == in和out,有什么(假设或代码)的例子,我应该总是使用out而不是ref。
既然ref更通用,为什么还要用out呢?它只是语法上的糖吗?
前几天有人问我他们什么时候应该使用参数关键字out而不是ref。虽然我(我认为)理解ref和out关键字之间的区别(之前已经问过了),最好的解释似乎是ref == in和out,有什么(假设或代码)的例子,我应该总是使用out而不是ref。
既然ref更通用,为什么还要用out呢?它只是语法上的糖吗?
当前回答
基本上ref和out都用于在方法之间传递对象/值
out关键字使参数通过引用传递。这类似于ref关键字,只不过ref要求在传递变量之前对其进行初始化。
out:参数没有初始化,必须在方法中初始化
ref:参数已经初始化,可以在方法中读取和更新。
引用类型的“ref”有什么用?
您可以将给定的引用更改为不同的实例。
你知道吗?
Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref argument and the other takes an out argument. You can't use the ref and out keywords for the following kinds of methods: Async methods, which you define by using the async modifier. Iterator methods, which include a yield return or yield break statement. Properties are not variables and therefore cannot be passed as out parameters.
其他回答
还是觉得需要好好总结一下,这就是我想出来的。
总结,
当我们在函数内部时,这就是我们如何指定变量数据访问控制,
in = R
out = W必须在R之前
参考 = R+W
解释,
in
函数只能读取该变量。
out
变量不能先初始化,因为, 函数必须先写后读。
ref
函数可以读/写该变量。
为什么要这样命名呢?
关注数据被修改的地方,
in
数据必须在输入(in)函数之前设置。
out
数据必须只在离开(out)函数之前设置。
ref
在输入函数之前必须设置数据。 在离开(out)函数之前可以设置数据。
使用out表示该参数未被使用,仅被设置。这有助于调用者理解您总是在初始化参数。
此外,ref和out不仅适用于值类型。它们还允许您重置引用类型从方法中引用的对象。
作为ref传递的参数必须在传递给方法之前初始化,而out形参在传递给方法之前不需要初始化。
需要注意的是,in在c# ver 7.2是一个有效的关键字:
The in parameter modifier is available in C# 7.2 and later. Previous versions generate compiler error CS8107 ("Feature 'readonly references' is not available in C# 7.0. Please use language version 7.2 or greater.") To configure the compiler language version, see Select the C# language version. ... The in keyword causes arguments to be passed by reference. It makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument. It is like the ref or out keywords, except that in arguments cannot be modified by the called method. Whereas ref arguments may be modified, out arguments must be modified by the called method, and those modifications are observable in the calling context.
读音: Out =只初始化/填充一个参数(参数必须为空),将其plain返回 Ref = reference,标准参数(可能带有value),但函数可以修改它。