C#参数类型总结

时间:2022-07-22
本文章向大家介绍C#参数类型总结,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

图1来自《图解C#》

[图1]

image.png

  • ref 和 out C#中的ref 和C++中的&运算符功能类似,但又有所不同。ref是传引用。值得注意的是 ref 和out在声明和使用的时候都必须写关键字。ref传入的参数必须要先赋值,而out则不必。这是这两者主要区别。
  1. 没使用ref之前的输出结果为20 50 20 50
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DrillOne
{
    class Num
    {
        public int var1 = 20;
    }
    class Test
    {
        public void Method(Num num)//这里并没有产生一个对象。只是在栈中产生了一个引用变量。
        {
            num.var1 = 50;
            Console.WriteLine("After change the value: {0}", num.var1);
            num = new Num();
            Console.WriteLine("After creat a object to num : {0}", num.var1);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            Num number = new Num();
            Console.WriteLine("Before call method:{0}", number.var1);
            test.Method(number);
            Console.WriteLine("After call method:{0}", number.var1);
            
        }
    }
}
  • 输出结果为:

image.png

  1. 使用ref之后的结果为:20 50 20 20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DrillOne
{
    class Num
    {
        public int var1 = 20;
    }
    class Test
    {
        public void Method(ref Num num)//这里并没有产生一个对象。只是在栈中产生了一个引用变量。
        {
            num.var1 = 50;
            Console.WriteLine("After change the value: {0}", num.var1);
            num = new Num();
            Console.WriteLine("After creat a object to num : {0}", num.var1);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            Num number = new Num();
            Console.WriteLine("Before call method:{0}", number.var1);
            test.Method(ref number);
            Console.WriteLine("After call method:{0}", number.var1);
            
        }
    }
}
  • 运行结果为

image.png

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DrillOne
{
    class Num
    {
        public int var1 = 20;
    }
    class Test
    {
        public void Method(out Num num,out int f1)//这里并没有产生一个对象。只是在栈中产生了一个一个引用变量。
        {
            num = new Num();
            f1 = 50;
            Console.WriteLine("{0}", num);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            Num number;
            int a;
            test.Method(out number, out a);
            Console.WriteLine("{0} {1:c}", number.var1, a);
        }
    }
}
  • 运行结果为:

image.png