C#练习笔记3:分部类分部方法,索引结合异常的使用

  分部类,分部方法,索引的运用虽说不常见,但是有时还是会用到的,还有一些异常的处理,

  

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

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {

            //分部类测试
            Test01 tt = new Test01();

            tt[0] = "adfad";
            tt[1] = "adsfa";
            tt[2] = "fadsaf";

            Console.WriteLine(tt[0]);
            Console.WriteLine(tt[3]);


            //分部类分部方法测试
            Test te = new Test();
            te.Add(8, 9);

            Console.Read();

        }

        /// <summary>
        /// 分部类,
        /// </summary>
        partial class Test
        {

            //分部方法
            partial void PrintSum(int x, int y);

            public void Add(int x, int y)
            {
                PrintSum(x, y);
            }
        }

        partial class Test
        {
            partial void PrintSum(int x, int y)
            {
                Console.WriteLine(x + y);
            }
        }


        class Test01
        {
            string str1;
            string str2;

            //索引的运用
       //类似于属性
public string this[int index] { set { switch (index) { case 0: str1 = value; break; case 1: str2 = value; break; default: //throw new IndexOutOfRangeException("索引越界"); Console.WriteLine("索引越界"); break; } } get { try { if (index == 0) return str1; if(index==1) return str2; } catch (Exception e) { Console.WriteLine(e.Message); } return "索引超出界限"; } } } } }

  运行结果:

  

原文地址:https://www.cnblogs.com/springword/p/6182886.html