如果你有一个强力搜索用户不知道数据类型,那么我们可以这样做吗?
if (search.Length > 0 && comboBox1.Text.Equals("Data Type Not Known"))
{
try
{
ParentGraph p = new ParentGraph(search);
}
catch (NoDataFoundException ndfe)
{
//it fails so try different data type
try
{
CompoundGraph c = new CompoundGraph(search);
}
catch(NoDataFoundException ndfe)
{
//failed so try final type
try
{
BatchGraph b = new BatchGraph(search);
}
catch(NoDataFoundException ndfe)
{
MessageBox.Show("Data could not be linked to a particular search")
}
}
}
}
答案 0 :(得分:4)
这会奏效,但它在两个方面很难看:
List<T>
,例如List<Func<string, object>>
并依次尝试每个工厂代表?TryGetData
具有out参数和bool
返回值(或者可能只是元组返回值) )。处理这种流程有例外并不适合我。答案 1 :(得分:0)
除了比你应该更频繁地抛出异常之外,看起来你的搜索构造函数可能会做更多的工作。我希望所有实例都使用light构造函数进行实例化,然后让它们在调用方法时执行实际工作,例如:
// initialize graph
IGraph p = new ParentGraph();
// get the results (although count may be zero)
IEnumerable<Result> results = p.GetResults(search); // never throws an exception
通用界面如下所示:
interface IGraph
{
IEnumerable<Result> GetResults(string search);
}
如果您的所有Graph实例都实现了IGraph,您可以像这样使用它们:
IEnumerable<IGraph> knownGraphs = new IGraph[]
{
new ParentGraph(),
new CompoundGraph(),
...
}
// get results from the first graph which can give them
foreach (IGraph graph in knownGraphs)
{
List<Result> results = graph.GetResults(search).ToList()
if (results.Count > 0)
return results;
}