不能将方法组转换为Action



我被这个错误卡住了,但不知道如何修复它。

我正试图将一个方法作为参数传递给另一个函数作为操作。我有一个定义了两个方法的接口:

//ISegment interface
void SetNodeA(in INode node);
void SetNodeB(in INode node);

接下来我创建一个段,我想把这个方法传递给另一个函数:

ISegment segment = GetSegment();
Execute(start, segment.SetNodeA);
Execute(end, segment.SetNodeB);

我的execute函数是这样的:

void Execute(in EndPoint point, in Action<INode> fnc)
{
Verify(segment);
Verify(point.Node);
fnc?.Invoke(point.Node); //set the node
}

问题是我得到这个错误:

参数2:不能从'method group'转换为'in Action'

不知道这里的method group是什么意思,也不知道如何修复它。

问题是您的SetNodeASetNodeB方法有in参数您试图通过Action<T>调用它们,这支持in,outref参数。

如果你需要为这些方法继续使用in,那么你可以通过创建一个自定义委托类型来实现这一点,并使用它来代替Action<T>:

public delegate void ActionWithInParam<T>(in T node);

那么,你的Execute方法应该是这样的:

void Execute(in EndPoint point, ActionWithInParam<INode> fnc)
{
Verify(segment);
Verify(point.Node);
fnc?.Invoke(point.Node); //set the node
}

您需要从SetNodeX签名中删除in参数修饰符,或者为第二个Execute参数使用自定义委托:

public interface ISegment
{
void SetNodeA(in INode node);
void SetNodeB(INode node); // in removed
}
public delegate void DelegateWithIn(in INode node);
void Execute(in EndPoint point, DelegateWithIn fnc)
{
}
void Execute1(in EndPoint point, Action<INode> fnc)
{
}
Execute(null, segment.SetNodeA); // uses custom delegate
Execute1(null, segment.SetNodeB); // uses Action

正如我在评论中提到的,ActionFunc委托不支持in,outref参数修饰符。

相关内容

最新更新