通常的接口實現多態spa
定義接口code
interface Ipeople { void say(); }
定義實現的類blog
public class man : Ipeople { public void say() { MessageBox.Show("man"); } } public class woman : Ipeople { public void say() { MessageBox.Show("woman"); } }
通常實現的方法接口
升級版string
添加自定義(這個網上好多)class
實現類foreach
調用方法方法
private static void NewMethod(string tpye) { Ipeople ib = null; var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(Ipeople)))) .ToArray(); foreach (var v in types) { var attribute = v.GetCustomAttributes(typeof(NameAttribute), false).FirstOrDefault(); if (attribute != null && ((NameAttribute)attribute).Name == tpye) { ib = (Ipeople)v.Assembly.CreateInstance(v.FullName); break; } } if (ib != null) ib.say(); }
這個能夠避免須要維護swich語句im