C# 关于out关键字的用法(一个方法返回多个值的问题)

来源:互联网 发布:网络延长器品牌 编辑:程序博客网 时间:2024/05/19 15:24
通常一个方法只能返回一个值,但是如果在某些时候,我们想要返回多个值,例如某个方法将一个浮点数分割成一个整数和一个小数返回去。这个时候我们就要用到out关键字。

如果用ref也可以解决,但是用ref需要在初始化的时候虚设一个值,并且还要给虚设值赋初始值。

复习输出值的格式初始化,复习了@的一个用法。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;namespace cxx{    class Testout    {        public int getParts(double n, out double frac)        {            int whole;            whole = (int)n;            frac = n - whole; //pass fractional小数 part back through frac             return whole;     //return integer portion 返回整数部分           }    }    class UseOut    {        static void Main()        {            Testout Tout = new Testout();            int i;            double f;            i = Tout.getParts(1234.05067891023343, out f);            Console.WriteLine("整数部分:" + i);            Console.WriteLine("小数部分:{0:#.###}" , f);            Console.WriteLine("小数部分:" + f);            Console.WriteLine(@"my name is shoneworn.welcome to my blog: www.cnblogs.com/shoneworn.注意看@的用法,是按照自己排版输出的。");            Console.ReadKey();        }    }   }

0 0
原创粉丝点击