zoukankan      html  css  js  c++  java
  • C#心得与经验(二)

      本周学到很多C#关于Interface, Array的知识,在这里简单复习一下几个易混的地方,重在理解。

    一、Interface

          使用as来避免多态时没有接口的Exception:

    Document [] folder  = new Document[5];
    for (int i = 0; i < 5; i++)
    {
      if (i % 2 == 0)
      {
        folder[i] = new BigDocument("Big Document # " + i);
      }
      else
      {
        folder[i] = new LittleDocument("Little Document # " + i);
      }
    }
    

     如果Little Document没有继承Read(), 直接调用会有Exception。

    foreach (Document doc in folder)
    {
            IStorable isDoc = doc as IStorable;
            if (isDoc != null)
            {
                    isDoc.Read();
            }
         else
         { Console.WriteLine("IStorable not supported");
    } //… }

    这个例子简单明了

      显式实现接口:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication2
    {
    
        class Program
        {
            interface IStorable
            {
                void Read();
                void Write();
            }
    
            interface ITalk
            {
                void Talk();
                void Read();
            }
    
            public class Document : IStorable, ITalk
             {
                public void Read() { Console.WriteLine("Read"); }
                public void Write() { Console.WriteLine("Write"); }
                void ITalk.Read() { Console.WriteLine("Read of ITalk"); }
                public void Talk() { Console.WriteLine("Talk"); }
            }
    
            static void Main(string[] args)
            {
                Document doc1 = new Document();
                doc1.Read();
                ITalk doc2 = doc1;
                doc2.Read();
            }
        }
    }
    

    1. 显式实现不用public

    2. 显式调用需要新建ITalk对象(见代码)。

    二、Array

      新建由(2,3)开始的3x5的数组:

    int[] lengthsArray = new int[2] { 3, 5 };
    int[] boundsArray = new int[2] { 2, 3 };
    Array multiDimensionalArray = Array.CreateInstance(typeof(string), lengthsArray, boundsArray);
  • 相关阅读:
    第十四周 Leetcode 315. Count of Smaller Numbers After Self(HARD) 主席树
    POJ1050 To the Max 最大子矩阵
    POJ1259 The Picnic 最大空凸包问题 DP
    POJ 3734 Blocks 矩阵递推
    POJ2686 Traveling by Stagecoach 状态压缩DP
    iOS上架ipa上传问题那些事
    深入浅出iOS事件机制
    iOS如何跳到系统设置里的各种设置界面
    坑爹的私有API
    业务层网络请求封装
  • 原文地址:https://www.cnblogs.com/funcode/p/4394603.html
Copyright © 2011-2022 走看看