c# - 传递给方法时参数是否按顺序求值?

标签 c#

参数传入方法时是否按顺序求值?

对于 Java 它总是正确的,对于 C 它不是,但是对于 C# 的答案是什么?

示例

string.Format("byte1={0} byte2={1} byte3={2}", 
  getNextByte(), 
  getNextByte(), 
  getNextByte());

int pos=0;
byte[] arr=new byte[] {1,2,3,4,5,6};
byte getNextByte()
{
  return arr[pos++];  
}

这个示例有效,但这只是运气还是规则?

最佳答案

是的,作为参数传递给方法的表达式总是从左到右求值。

来自 C# 4.0 语言规范:

7.5.1.2 Run-time evaluation of argument lists

During the run-time processing of a function member invocation (§7.5.4), the expressions or variable references of an argument list are evaluated in order, from left to right, [...]

关于c# - 传递给方法时参数是否按顺序求值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7359996/

相关文章:

c# - 在调用方法之前将对象存储在变量中有好处吗?

c# - 防止 Entity Framework 为导航属性插入值

c# - 如何访问FlipView内DataTemplate内的xaml控件

c# - 通过 uniqueidentifier 选择后使用 dapper 更新多条记录

c# - 我如何在 silverlight 中将 Xaml 转换为 Rtf?

c# - C#中比较不同时区时间的代码示例

c# - 如何将 Linq 扩展方法与 CodeFluent 实体模板一起使用?

c# - ASP.NET CORE 3.1 读取 session 时未分配初始值时出现 NULL 异常错误

c# - 来自外部应用程序的 Access 数据库中日期字段的月份名称 (C#)

c# - 从 .NET 1.1 升级到 .NET 2.0,会发生什么?