2
我必须实现一个表达式的调用图,如Id = Id(Param);
,这不是问题。调用图IEnumerator
现在我必须实现一个枚举器,它在满足顺序依赖关系的调用中一次列出所有拓扑顺序中的一个。
这就是麻烦。
这是调用图一个简单的节点:
class CallGraphNode
{
private string name;
public List<CallGraphNode> dependents = new List<CallGraphNode>();
public int dependencies;
private bool executed = false;
public bool Executable { get { return dependencies == 0; } }
public bool Executed { get { return executed; } set { executed = value; } }
public CallGraphNode(string name)
{
this.name = name;
dependencies = 0;
}
public override string ToString()
{
return name;
}
public void AddDependent(CallGraphNode n)
{
dependents.Add(n);
}
}
这是调用图类本身:
class CallGraph : IEnumerable<List<CallGraphNode>>
{
public List<CallGraphNode> nodes = new List<CallGraphNode>();
public void AddNode(CallGraphNode n)
{
nodes.Add(n);
}
public static void Show(IEnumerable<CallGraphNode> n)
{
foreach (CallGraphNode node in n)
{
Console.Write("{0} ", node);
}
Console.WriteLine();
}
static IEnumerable<List<CallGraphNode>> EnumerateFunctions(List<CallGraphNode> executable, List<CallGraphNode> res)
{
if (executable.Count == 0)
yield return res;
else foreach (CallGraphNode n in executable)
{
if (!n.Executed)
res.Add(n);
List<CallGraphNode> next_executable = new List<CallGraphNode>(executable);
executable.Remove(n);
foreach (CallGraphNode m in n.dependents)
if (--m.dependencies == 0)
next_executable.Add(m);
foreach (List<CallGraphNode> others in EnumerateFunctions(next_executable, res))
yield return others;
foreach (CallGraphNode m in n.dependents)
m.dependencies++;
if (!n.Executed)
res.Remove(n);
}
}
IEnumerator<List<CallGraphNode>> IEnumerable<List<CallGraphNode>>.GetEnumerator()
{
List<CallGraphNode> executable = new List<CallGraphNode>();
foreach (CallGraphNode n in nodes)
if (n.Executable || n.Executed)
executable.Add(n);
List<CallGraphNode> output = new List<CallGraphNode>();
foreach (List<CallGraphNode> list in EnumerateFunctions(executable, output))
yield return list;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{ throw new NotImplementedException(); }
}
现在的问题是,它只是将无法正常工作。当我尝试创建一个IEnumerator
并为其分配GetEnumerator()
返回值,我得到一个铸造的错误,这就是诚实跟我想象试图这样做的时候:
IEnumerator<List<CallGraphNode>> lt = cg.GetEnumerator();
然后我试着:
System.Collections.Generic.List<CallGraphNode>.Enumerator en = cg.nodes.GetEnumerator();
这可行,但方法EnumerateFunctions
永远不会被调用,枚举器只包含图形节点的原始列表。
任何想法?
我选择了明确的实现方式ñ,它像一个魅力工作,谢谢。但EnumerateFunctions方法永远不会被调用。很奇怪。 – Cancer 2012-07-09 20:22:33
@ user1512923:你真的在迭代结果吗?如果不是,那么'GetEnumerator'方法中的* none *代码将被调用。迭代器块的一部分是代码被懒惰地执行。 – 2012-07-09 21:33:46
感谢Jon,你是对的,我设法让它工作迭代结果!我认为代码本来会被调用的。非常感谢 :) – Cancer 2012-07-09 22:19:47