2011-11-25 48 views
0

我已经编写了一个模板化的digraph类(Graph<Generic>)供Djikstra's在我正在进行的项目中使用。其中,它为DataContainer对象分配内存,该对象使用AdjacencyList实例(实现IDataContainer)进行初始化,以便跟踪所有节点和边缘。我还编写了一个AdjacencyMatrix类(它也实现了IDataContainer),我希望在某些情况下可以动态使用它。如何判断哪个类用于在C#中管理其数据?

现在我创建了一个有向图通过以下调用:

Graph<string> graph = new Graph<string>(); 

而在我的图表,我创建了我的数据容器:

IDataContainer<Generic> data; 
public Graph() 
{ 
    data = new AdjacencyList<Generic>(); 
} 

理想情况下,我想传递我想要使​​用的数据结构(列表与矩阵),当我打电话给构造函数,如:

Graph<AdjacencyMatrix, string> graph = new Graph<AdjacencyMatrix, string>(); 

但我不是qui确定如何通过模板化的类型。我能以这样的方式模板它允许调用,比如:

Graph<AdjacencyList<string>, string> graph = new Graph<AdjacencyList<string>, string>(); 

但是,当我走在类来创建邻接表(其中public class Graph<Container, Generic> where Container : new()与按http://msdn.microsoft.com/en-us/library/x3y47hd4(v=vs.80).aspx where子句)有:

data = new Container(); 

我得到的错误:

Cannot implicitly convert type 'Container' to 'GraphDataContainer<Generic>'. An explicit conversion exists (are you missing a cast?) 

我很可能包括就解决了错误的类型转换含蓄,但我认为这样的事实,在有错误所有在试图创建实例时(将子类传递给GraphDataContainer时)都表明这里还有其他错误。它是我的继承,还是它在混乱的构造函数调用中令人费解的事情(如果你能想到一个更干净的方法,会非常感激!)?

有没有办法告诉一个类,当它最初被构造时使用哪个类来管理它的数据?

回答

1

什么

public class Graph<Container> where Container : DataContainer, new() 

然后你可以使用

var graph = new Graph<AdjacentList>() 
var anotherGraph = new Graph<AdjacentMatrix>() 

,并在Graph

this.container = new Container(); 

这可能是也实现与接口

例如,考虑Graph类构造器。你可以做类似:

public Graph(IContainer container) 
{ 
    this.container = container; 
} 

,并有AdjacentListAdjacentMatrix实施​​。

+0

太棒了。谢谢!小编辑:'new()'必须是where子句后面列出的最后一个东西,所以它应该是'Where Container:DataContainer,new()'。 – drusepth

相关问题