• 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);
  • 相关阅读:
    什么是php面向对象及面向对象的三大特性
    php类的定义与实例化方法
    php面向对象之$this->用法简述
    url的主要功能是什么
    PHP字符串比较函数详解
    PHP截取字符串函数substr()函数实例用法详解
    php 读取文件
    php 正则达达示中的模式修正符
    php正则表示中的元字符
    php 正则表达示中的原子
  • 原文地址:https://www.cnblogs.com/funcode/p/4394603.html
Copyright © 2020-2023  润新知