10.ref和out的基本使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _9ref和out
{
public class student
{
public int StudentId { get; set; }
public string StudentNmae { get; set; }
    //使用out关键字可以有多个返回值。out参数也必须赋值。
    //out关键字使用引用方式传递,可以使用"字典集合"方式返回多个参数。
    public string GetStudenT(int Age, out int age)
    {
        age = Age;
        string info = string.Format("学号为:{0},姓名为:{1},", StudentId, StudentNmae);
        return info;
    }
}
class Program
{
    static void Main(string[] args)
    {
        //使用out关键字
        student objstu = new student()
        {
            StudentNmae = "张三",
            StudentId = 1000
        };
        int Stuage = 0;
        string info = objstu.GetStudenT(20, out Stuage);
        //使用ref关键字
        int a = 1;
        int b = 2;
        Console.WriteLine("ref交换前:a={0},b={1}", a, b);
        Swap1(ref a, ref b);
        Console.WriteLine("ref交换后:a={0},b={1}", a, b);
        Console.WriteLine("------------------------------------");
        int A = 1;
        int B = 2;
        Console.WriteLine("值类型交换前:A={0},B={1}", A, B);
        Swap2( A,  B);
        Console.WriteLine("值类型交换后:A={0},B={1}", A, B);
        Console.Read();
    }
    /// <summary>
    /// 交换a,b两个变量的值。使用ref关键字可以降值类型按照引用类型传递。
    /// </summary>
    /// <param name="a"></param>
    /// <param name="b"></param>
    private static void Swap1(ref int aa, ref int bb)
    {
        int temp = aa;
        aa = bb;
        bb = temp;
        Console.WriteLine("ref方法内:aa={0},bb={1}", aa, bb);
    }
    /// <summary>
    /// 交换a,b两个变量的值。
    /// </summary>
    /// <param name="a"></param>
    /// <param name="b"></param>
    private static void Swap2( int aa,  int bb)
    {
        int temp = aa;
        aa = bb;
        bb = temp;
        Console.WriteLine("值类型方法内:AA={0},BB={1}", aa, bb);
    }
}
}
 
                    
                 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号