一、泛型
泛型跟其他的东西具有良好的正交性。
即存在泛型类、泛型接口、泛型委托等等等。
泛型对于成员膨胀和类型膨胀具有良好的作用。下面我们来看看实例。
本次实例讲的是一个杂货铺,一开始只卖苹果:
namespace ConsoleAppPractice
{
class Program
{
static void Main()
{
Store store = new Store();
Box box = new Box();
Apple apple = new Apple(AppleColor.Red);
store.Wrap(box, apple);
store.Sold(box);
}
}
enum AppleColor
{
Red,
Green,
Yellow,
}
class Store
{
public void Wrap(Box box,Apple apple)
{
Console.WriteLine("I will wrap the apple.");
box.apple = apple;
}
public void Sold(Box box)
{
Console.WriteLine("I will sold you {0} {1} in the box.",box.apple.Color,box.apple.GetType().Name);
}
}
class Box
{
public Apple apple { get; set; }
}
class Apple
{
public AppleColor Color { get; set; }
public Apple(AppleColor color)
{
Color = color;
}
}
}
然后还想卖书,这时候有一种做法,是再声明一个盒子只装书。这显然会随着商品种类增多造成类型膨胀。或者是在盒子类里再多一个书的属性,这显然会造成成员膨胀。而如果使用接口,又感觉划不来。这时候,我们可以考虑使用泛型。
namespace ConsoleAppPractice
{
class Program
{
static void Main()
{
Store store = new Store();
Thing<AppleColor> apple = new Thing<AppleColor>(AppleColor.Red, "Apple");
Thing<BookName> book = new Thing<BookName>(BookName.Snow_Whites, "Book");
Box<Thing<AppleColor>> appleBox = new Box<Thing<AppleColor>>();
Box<Thing<BookName>> bookBox = new Box<Thing<BookName>>();
store.Wrap(appleBox, apple);
store.Sold(appleBox);
store.Wrap(bookBox, book);
store.Sold(bookBox);
}
}
enum AppleColor
{
Red,
Green,
Yellow,
}
enum BookName
{
Snow_Whites,
The_Little_Prince,
Go_West,
}
class Store
{
public void Wrap<T>(Box<T> box,T thing)
{
box.thing = thing;
}
public void Sold<T>(Box<T> box)
{
Console.WriteLine("I will sold you {0} in the box.",box.thing.GetType().GetProperty("thingName").GetValue(box.thing));
}
}
class Box<T>
{
public T thing { get; set; }
}
class Thing<T>
{
public T Property { get; set; }
public string thingName { get; set; }
public Thing(T t,string name)
{
Property = t;
thingName = name;
}
}
}
我能想到的最好方法。
注意一下泛型方法、泛型类的定义
注意main函数里调用方法那几行,泛型可以自动推测类型。
接下来我们看看泛型接口的实例。
namespace ConsoleAppPractice
{
class Program
{
static void Main()
{
Student<ulong> stu1 = new Student<ulong>() { ID = 102034};
stu1.Report();
Student<string> stu2 = new Student<string>() { ID = "Mike" };
stu2.Report();
}
}
interface IUnique<TId>
{
TId ID { get; set; }
}
class Student<TId> : IUnique<TId>
{
public TId ID { get; set; }
public void Report()
{
Console.WriteLine("I am a student.My ID is {0}.",ID);
}
}
}
二、Partial类
允许我们把一个类的代码分成多个类、且可以用不同的语言来编写。这些被分成的多个类可以以不同的速度进行版本更新。