您可以使用Interface + Reflection來避免在數據庫中存儲算法名稱。
創建一個接口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
/// <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;
}
}
}
}
我的基本問題的非LINQ的版本是 - 怎麼知道實例是什麼類型?我所擁有的解決方案並不高雅,我認爲這種情況非常普遍,我希望一些實際做到這一點的人可以給我提供建議。 – satyajit 2009-07-25 02:39:11