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);
  • 相关阅读:
    使用ServiceStackRedis链接Redis简介
    浅谈SQL SERVER中事务的ACID
    Sql Server查询性能优化之走出索引的误区
    Redis命令总结
    TSQL查询进阶—理解SQL Server中的锁
    SQL Server 2005 分区表实践——分区切换
    SQL Server Profiler 模板
    深入浅出SQL Server中的死锁
    不同的单元中的类可以共用同一个命名空间
    从硬盘上装xp手记(2005.8.14 )
  • 原文地址:https://www.cnblogs.com/funcode/p/4394603.html
Copyright © 2011-2022 走看看