您可以使用接口 + 反射来避免将算法名称存储在数据库中。
创建一个接口 IMySortingAlgorithms 为,
public interface IMySortingAlgorithms
{
string Name { get; }
string[] Sort(string[] input);
}
现在,编写一个使用反射来获取排序算法的工厂。
public static class MyAlgoFactory
{
private static Dictionary<string, IMySortingAlgorithms> m_dict;
/// <summary>
/// For all the assmeblies in the current application domain,
/// Get me the object of all the Types that implement IMySortingAlgorithms
/// </summary>
static MyAlgoFactory()
{
var type = typeof(IMySortingAlgorithms);
m_dict = AppDomain.CurrentDomain.GetAssemblies().
SelectMany(s => s.GetTypes()).
Where(p => {return type.IsAssignableFrom(p) && p != type;}).
Select(t=> Activator.CreateInstance(t) as IMySortingAlgorithms).
ToDictionary(i=> i.Name);
}
public static IMySortingAlgorithms GetSortingAlgo(string name)
{
return m_dict[name];
}
}
你所有的排序算法现在都可以实现这个接口。
public class MySortingAlgo1 : IMySortingAlgorithms
{
#region IMySortingAlgorithms Members
public string Name
{
get { return "MySortingAlgo1"; }
}
public string[] Sort(string[] input)
{
throw new NotImplementedException();
}
#endregion
}
这样,每当您创建新类进行排序时,您都不需要将类名添加到数据库中。
以下是 MyAlgoFactory 的非 Linq 版本
/// <summary>
/// For all the assmeblies in the current application domain,
/// Get me the object of all the Types that implement IMySortingAlgorithms
/// </summary>
static MyAlgoFactory()
{
m_dict = new Dictionary<string, IMySortingAlgorithms>();
var type = typeof(IMySortingAlgorithms);
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type p in asm.GetTypes())
{
if (type.IsAssignableFrom(p) && p != type)
{
IMySortingAlgorithms algo = Activator.CreateInstance(p)
as IMySortingAlgorithms;
m_dict[algo.Name] = algo;
}
}
}
}