I am stuck with this error but not sure how to fix it.
I am trying to pass a method as a parameter to another function as an action. I have an interface which defines two methods:
//ISegment interface
void SetNodeA(in INode node);
void SetNodeB(in INode node);
Next I create a segment and I want to pass this method into another function:
ISegment segment = GetSegment();
Execute(start, segment.SetNodeA);
Execute(end, segment.SetNodeB);
My execute function looks like this:
void Execute(in EndPoint point, in Action<INode> fnc)
{
Verify(segment);
Verify(point.Node);
fnc?.Invoke(point.Node); //set the node
}
Problem is i get this error:
Argument 2: cannot convert from 'method group' to 'in Action'
Not sure what it means by method group here or how to fix it.
The problem is that your SetNodeA
and SetNodeB
methods have an in
parameter and you're trying to invoke them via an Action<T>
, which does not support in
, out
, or ref
parameters.
If you need to keep using in
for those methods, then you can achieve that by creating a custom delegate type and use that instead of Action<T>
:
public delegate void ActionWithInParam<T>(in T node);
Then, your Execute
method would be something like this:
void Execute(in EndPoint point, ActionWithInParam<INode> fnc)
{
Verify(segment);
Verify(point.Node);
fnc?.Invoke(point.Node); //set the node
}
You need either remove in
parameter modifier from SetNodeX
signature or use custom delegate for second Execute
parameter:
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
As I mentioned in the comments Action
and Func
delegates does not support in
, out
and ref
parameter modifiers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.