为了消除switch,找设计模式,设计模式没找到自己能理解的,又找到泛型
以下例子能说明泛型的一种用途
using System;
using System.Collections;
public class m
{
public static void Main()
{
ArrayList list = new ArrayList();
list.Add(3);
list.Add(4);
//list.Add(5.0);
int total = 0;
foreach (int val in list)
{
total = total + val;
}
Console.WriteLine("Total is {0}", total);
}
}
以上代码编译、运行都很正常。如果把注释拿掉,则编译会通过,运行却出错。
而用泛型来处理的话:
using System;
using System.Collections.Generic;
public class m
{
public static void Main()
{
List<int> list = new List<int>();
list.Add(3);
list.Add(4);
list.Add(5.0);
int total = 0;
foreach (int val in list)
{
total = total + val;
}
Console.WriteLine("Total is {0}", total);
}
}
编译就通不过。
泛型还可以用于类
using System;
public class m
{
public static void Main()
{
Create1<C1> a = new Create1<C1>();
a.GetC1().show1();
Create1<M1> b = new Create1<M1>();
b.GetC1().show2();
}
}
public class Create1<T>
where T : new()
{
public T GetC1()
{
return new T();
}
}
public class C1
{
public virtual void show1()
{
Console.WriteLine("C1");
}
}
public class M1
{
public virtual void show2()
{
Console.WriteLine("M1");
}
}
如果在VS2008中输入b.GetC1().后,系统会自动有show2这个方法,有点牛!
不过我还是不知道如何利用它来消除switch。
另一种方法是反射,这要消除switch比较容易,但要把两个类给分在不同的DLL,不然我不会
C1.cs
using System;
public class C1
{
public virtual void show1()
{
Console.WriteLine("C1");
}
}
M1.cs
using System;
public class M1
{
public virtual void show2()
{
Console.WriteLine("M1");
}
}
主代码如下:
using System;
using System.Reflection;
public class m
{
public static void Main()
{
Create1 a = new Create1();
((C1)a.GetC1("C1")).show1();
Create1 b = new Create1();
((M1)b.GetC1("M1")).show2();
}
}
public class Create1
{
public object GetC1(string className)
{
Assembly asm = Assembly.LoadFrom(className + ".dll");
object o = asm.CreateInstance(className);
return o;
}
}
编译命令如下:
csc /t:library C1.cs
csc /t:library M1.cs
csc /r:c1.dll;m1.dll t.cs
至此,自己头也昏了,虽然还可以把泛型与反射结合起来,但这究竟能干什么?我消除switch的目标还是没有着落。
再继续找,终于找到一篇文章:
http://noriko529784.blog.163.com/blog/static/30429996200782403832721/
把代码写成这样:
using System;
using System.Reflection;
public class m
{
public static void Main()
{
Create1 a = new Create1();
a.GetC1("C1").show1();
Create1 b = new Create1();
b.GetC1("M1").show1();
}
}
public class Create1
{
public C GetC1(string className)
{
C o = null;
Type type = Type.GetType(className, true);
o = (C) Activator.CreateInstance(type);
return o;
}
}
public class C
{
public virtual void show1()
{
}
}
public class C1 : C
{
public override void show1()
{
Console.WriteLine("C1");
}
}
public class M1 : C
{
public override void show1()
{
Console.WriteLine("M1");
}
}
编译,即可OK。