c# 运算符重载 异常处理 File

一, 1.运算符重载的声明方式:operator 关键字

  People people = new People() { ID =10,Name ="张三"};
  People people1 = new People() { ID=20,Name ="李四"};

 People newPeople1 = people + people1;
        Console.WriteLine(newPeople1.ID)//10 20
       Console.WriteLine(newPeople1.Name);//张三 李四

  public int ID {get;set;}
        public string Name { get;set;}

       public static People operator +(People people, People people1)
        {

            return new People() { ID = people.ID + people1.ID, Name = people.Name +                  people1.Name };

        }

              2.必须用public修饰且必须是类的静态的方法
              3.重载运算符的方法 不用主动调用 只要使用重载的运算符就相当调用了方法
              4.运算符只能采用值参数,不能采用ref或out参数
              5.重载运算符的返回值不一定必须是自己,但一定不能是void
 

二,引起异常的语句  系统默认会抛出异常信息

try
            {
                // 引起异常的语句
                int[] array = { 1, 2 };
                array[3] = 10;
              
            }
            catch //有异常会输出catch中的内容
            {
                Console.WriteLine("有异常出现");
            }
            finally 
            {
                Console.WriteLine("有没有异常都执行");
            }

三,File 

1,创建文件

  string filePath = @"D:\myFile.txt";
  FileStream fileStream = File.Create(filePath);

2.像地址里写入 ABC

  string path = @"D:\myFile.txt";
     StreamWriter streamWriter = new StreamWriter(path);
     streamWriter.WriteLine("ABC");

3.读出 sr 内容

 string path = @"D:\myFile.txt";
            StreamReader sr = new StreamReader(path, Encoding.UTF8 );//万国符
            string content = sr.ReadToEnd();
            Console.WriteLine(content);

 private static void FileDataAppend() {

            string path = @"D:\myFile.txt";

            if (!File.Exists(path))  //检查文件是否存在
            {
                FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);  //创建
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("input text");  //写入内容,自定义

                sw.Close();
                fs.Close();
            }
            else
            {
                FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);  //追加写入
                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine("567");  //写入内容,自定义

                sw.Close();
                fs.Close();
            }
        }

4.删除内容

 string path = @"D:\C#创建的文件夹";
     Directory.CreateDirectory(path);//把文件夹存入path
      DirectoryInfo directoryInfo = new DirectoryInfo(path);//指定文件 path
        FileInfo[] fileInfo = directoryInfo.GetFiles();//获取指定目录里面的所有文件

 fileInfo2.Delete();//删除 fileInfo 内容

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值