Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# ref out

作者:饮尽孤单   发布日期:2025-11-11   浏览:115

using System;

public class Program
{
    public static void Main()
    {
        int num = 10;
        int result;

        // 使用 ref 关键字传递参数
        Increment(ref num);
        Console.WriteLine($"After increment using ref: {num}");

        // 使用 out 关键字传递参数
        Divide(10, 3, out result);
        Console.WriteLine($"Division result using out: {result}");
    }

    // ref 参数必须在调用前初始化
    public static void Increment(ref int number)
    {
        number += 5;
    }

    // out 参数不需要在调用前初始化,但必须在方法体内赋值
    public static void Divide(int a, int b, out int result)
    {
        result = a / b;
    }
}

解释说明

  1. ref 关键字:

    • ref 关键字用于将参数按引用传递给方法。这意味着方法可以修改传递的参数,并且这些修改会反映在调用方中。
    • 在调用带有 ref 参数的方法时,传递的参数必须已经初始化。
  2. out 关键字:

    • out 关键字也用于将参数按引用传递给方法,但它与 ref 不同的是,传递的参数不需要在调用前初始化。
    • 方法必须确保在返回之前为 out 参数赋值。
  3. 示例代码:

    • Increment 方法使用 ref 关键字来增加传入的整数。
    • Divide 方法使用 out 关键字来计算两个整数的商,并将结果返回给调用方。

上一篇:c# new

下一篇:c#矩阵运算

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站