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);

浙公网安备 33010602011771号