欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#函数的参数传递2(ref\out)

程序员文章站 2022-06-13 08:34:13
using System; namespace class1 { class program { static void Main(string[] args) { Console.Write("请输入a="); double a = double.Parse(Console.ReadLine()) ......
using system;
namespace class1
{
    class program
    {
        static void main(string[] args)
        {
            console.write("请输入a=");
            double a = double.parse(console.readline());
            console.write("请输入b=");
            double b = double.parse(console.readline());
            console.writeline("first");
            console.write("\t{0}  {1}", a, b);
            swap(a,b);
            console.writeline("\nsecond");
            console.writeline("\t{0}  {1}" ,a,b);
            swap1(ref a, ref b);//实际参数也加上ref
            console.writeline("\nthird");
            console.writeline("\t{0}  {1}", a, b);
            console.write("请输入r=");
            double r = double.parse(console.readline());
            double s = mianjizhouchang(r, out double c);//这里的out也可以用ref代替,这个时候要为c赋初值
            console.writeline("面积是{0},周长是{1}",s,c);
        }
        static void swap(double x, double y) {
            double z = x;
            x = y;
            y = z;
        }
        /// <summary>
        /// 使形式参数变成引用传递,加上ref
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        static void swap1(ref double x, ref double y)
        {
            double z = x;
            x = y;
            y = z;
        }
        /// <summary>
        /// out应用
        /// </summary>
        /// <param name="r"></param>
        /// <param name="zhouchang"></param>
        /// <returns></returns>
        static double mianjizhouchang(double r,out double zhouchang) {
            double s = math.pi * r * r;
            zhouchang = 2 * math.pi * r;
            return s;
        }
    }
}

C#函数的参数传递2(ref\out)