您的位置:首页 > 编程语言 > C#

C#源代码—值类型参数演示,引用类型参数演示

2016-01-13 11:26 405 查看
值类型参数演示

using System;
class Swaper
{
    public void Swap(int x,int y)      //被调用方,其中x和y是整型形参
    {
        int temp;
        temp = x;
        x = y;
        y = temp;
        Console.WriteLine("交换之后:{0},{1}", x, y);
    }
}
class TestMethod
{
    static void Main()                  //调用方,其中a和b是整型实参
    {
        Swaper s = new Swaper();        //创建对象               
        Console.WriteLine("请任意输入两个整型数:");
        int a = Convert.ToInt32(Console.ReadLine());
        int b = Convert.ToInt32(Console.ReadLine());
        s.Swap(a,b);                    //调用并传递参数
        Console.WriteLine("交换之前:{0},{1}", a, b);
    }
}


引用类型参数演示

using System;
class Swaper
{
    public void Swap(ref int x,ref int y)      //被调用方,其中x和y是引用型形参
    {
        Console.WriteLine("形参的值未交换:{0},{1}", x, y);
        int temp;
        temp = x;
        x = y;
        y = temp;
        Console.WriteLine("形参的值已交换:{0},{1}", x, y);
    }
}
class TestMethod
{
    static void Main()                  //调用方,其中实参是a和b的引用
    {
        Swaper s = new Swaper();        //创建对象               
        Console.WriteLine("请任意输入两个整型数:");
        int a = Convert.ToInt32(Console.ReadLine());
        int b = Convert.ToInt32(Console.ReadLine());
        s.Swap(ref a,ref b);                    //调用并传递参数
        Console.WriteLine("实参的值已交换:{0},{1}", a, b);
    }
}


引用类型参数演示

using System;
class Analyzer
{
    //从文件路径中分离路径和文件名,定义了两个输出参数
    public void SplitPath(string path,out string dir,out string filename)
    {
        int i;
        //寻找路径和文件名之间的间隔符\或:所在位置
        for (i = path.Length; i >=0; i--)
        {
            char c = path[i - 1];
            if (c == '\\' || c == ':')
                break;
        }
        //提取路径和文件名
        dir = path.Substring(0, i-1);   //0为起始位置,i-1为子字符串长度
        filename = path.Substring(i);//从i取,如String a = “abc”;a.substring(1) 为bc
    }
}
class TestMethod
{
    static void Main()                  //调用方,其中实参dir和file是输出参数
    {
        Analyzer a = new Analyzer();    //创建对象               
        Console.WriteLine(“请输入一个文件的路径:");
        string path  = Console.ReadLine();
        string dir, file;  //没有赋初值
        a.SplitPath(path, out dir, out file);   //调用方法
        Console.WriteLine(“文件所在目录:{0}\n文件名:{1}", dir, file);
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: