How to use anonymous generic delegate in C # 2.0
I have a class called NTree:
class NTree<T>
{
delegate bool TreeVisitor<T>(T nodeData);
public NTree(T data)
{
this.data = data;
children = new List<NTree<T>>();
_stopTraverse = false;
}
...
public void Traverse(NTree<T> node, TreeVisitor<T> visitor)
{
try
{
_stopTraverse = false;
TraverseInternal(node, visitor);
}
finally
{
_stopTraverse = false;
}
}
private void TraverseInternal(NTree<T> node, TreeVisitor<T> visitor)
{
if (_stopTraverse)
return;
if (!visitor(node.data))
{
_stopTraverse = true;
}
foreach (NTree<T> kid in node.children)
TraverseInternal(kid, visitor);
}
When I try to use Traverse with an anonymous delegate, I get:
Argument "2": Cannot convert from "anonymous method" to "NisConverter.TreeVisitor"
The code:
tTable srcTable = new tTable();
DataRow[] rows;
rootTree.Traverse(rootTree, delegate(TableRows tr)
{
if (tr.TableName == srcTable.mappingname)
{
rows = tr.Rows;
return false;
}
});
This, however, throws no errors:
static bool TableFinder<TableRows>(TableRows tr)
{
return true;
}
...
rootTree.Traverse(rootTree, TableFinder);
I tried putting "arrowhead-parenthisis" and everything for the anonymous delegate, but it just doesn't work. Please help me!
Thanks and BR-Matti
a source to share
The anonymous delegate you sent the message to did not return a boolean value (most likely a value true
if if(...)
guard false
). So the signature is actually void (TableRow)
instead bool (TableRow)
, and the compiler cannot perform the conversion.
So the syntax should be:
tTable srcTable = new tTable(); DataRow[] rows; rootTree.Traverse(rootTree, delegate(TableRows tr)
{
if (tr.TableName == srcTable.mappingname)
{
rows = tr.Rows;
return false;
}
return true;
});
a source to share
The TreeVisitor declaration is incorrect: it introduces a new type parameter (which conflicts with NTree's declaration). Just remove the template material and you get:
delegate bool TreeVisitor(T nodeData);
Then you can:
class X
{
void T()
{
NTree<int> nti = new NTree<int>(2);
nti.Traverse(nti, delegate(int i) { return i > 4; });
}
}
a source to share