C#中static静态变量 字符串拷贝

1、代码功能为字符串拷贝

2、代码环境为Visual Studio 2013

3、创建的为控制台应用程序


C#中static静态变量修饰类A里面的方法时,在另一个类B里面想调用类A的方法时,无需再次创建一个新的对象,代码分析如下:

程序的入口主函数Main,Program为类名,里面调用string_)copy类下面的str_copy函数方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace string_copy
{
    class Program
    {
        static void Main(string[] args)
        {
            int rv = 0;
            char[] src = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!'};
            char[] dest = new char[src.Length]; //根据原字符数组来定义目标字符数组的大小

            rv = string_copy.str_cpy(dest, src);    //调用string_copy类下面的str_cpy函数方法,无需再创建一个新的对象
            if (0 == rv)
            {
                Console.WriteLine(dest);    //打印目标数组
            }
            else
            {
                Console.WriteLine("内容是空的");
            }
            Console.ReadKey();
        }
    }
}
同工程下,新建一个.cs文件,打开文件会自动创建一个类,类名为文件名,string_copy为类名


string_copy类里面的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace string_copy
{
    class string_copy   //类
    {
        //静态的函数方法
        //参数char[] to为目标字符数组;char[] from为原字符数组
        public static int str_cpy(char[] to, char[] from)   
        {
            int i = 0;

            if (0 == from.Length)   
            {
                return -1;  //输入的字符为空
            }

            for (i = 0; i < from.Length; i++)
            {
                to[i] = from[i];    //把原字符数组的值传递给目标字符数组
            }

            return 0;
        }
    }
}
打印结果:

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值