[英]how to use anonymous generic delegate in C# 2.0
I have a class called NTree: 我有一个叫做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 anonymous delegate I get: 当我尝试将Traverse与匿名委托一起使用时,我得到:
Argument '2': cannot convert from 'anonymous method' to 'NisConverter.TreeVisitor' 参数“ 2”:无法从“匿名方法”转换为“ 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 produces no errors: 但是,这不会产生任何错误:
static bool TableFinder<TableRows>(TableRows tr)
{
return true;
}
... ...
rootTree.Traverse(rootTree, TableFinder);
I have tried to put "arrowhead-parenthisis" and everything to anonymous delegate but it just does not work. 我试图将“箭头括号”和所有内容放到匿名委托中,但这是行不通的。 Please help me!
请帮我!
Thanks & BR -Matti 谢谢&BR-马蒂
The anonymous delegate you posted lacks the return of a boolean value (most probably the value true
when the if(...)
guard is false
. Thus, it signature is actually void (TableRow)
instead of bool (TableRow)
, and the compiler is unable to make the conversion. 您发布的匿名委托缺少布尔值的返回值(当
if(...)
保护为false
时,很可能返回true
值。因此,它的签名实际上是void (TableRow)
而不是bool (TableRow)
,并且编译器无法进行转换。
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;
});
The declaration of TreeVisitor is wrong: it introduces a new type parameter (which conflicts with the declaration of NTree). TreeVisitor的声明是错误的:它引入了一个新的类型参数(与NTree的声明冲突)。 Just remove the template stuff and you get:
只需删除模板内容,您将获得:
delegate bool TreeVisitor(T nodeData);
Then you can have: 然后您可以拥有:
class X
{
void T()
{
NTree<int> nti = new NTree<int>(2);
nti.Traverse(nti, delegate(int i) { return i > 4; });
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.