Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将方法(带ref参数)作为参数传递_C#_Methods - Fatal编程技术网

C# 将方法(带ref参数)作为参数传递

C# 将方法(带ref参数)作为参数传递,c#,methods,C#,Methods,在我的特定用例中,我有几个地方可以互换地使用interlocated.Increment和interlocated.Decrement,因此我想将逻辑合并到一个方法中,并传递要调用的正确方法,作为参数: if (Interlocked.Increment(ref x) == something) { DoThis(); } else { DoThat(); } 还有另一个我喜欢的地方: if (Interlocked.Decrement(ref x) == something)

在我的特定用例中,我有几个地方可以互换地使用
interlocated.Increment
interlocated.Decrement
,因此我想将逻辑合并到一个方法中,并传递要调用的正确方法,作为参数:

if (Interlocked.Increment(ref x) == something)
{
    DoThis();
}
else
{
    DoThat();
}
还有另一个我喜欢的地方:

if (Interlocked.Decrement(ref x) == something)
{
    DoThis();
}
else
{
    DoThat();
}
其理念是整合为:

void Foo(Action<ref int> interlockedOp)
{
    if (interlockedOp(ref x) == something)
    {
        DoThis();
    }
    else
    {
        DoThat();
    }    
}
void Foo(动作联锁操作)
{
如果(互锁上(参考x)=某物)
{
DoThis();
}
其他的
{
DoThat();
}    
}
但是
操作
部分没有编译

有没有其他方法可以实现这一点?

即使编译了
操作,也不会起作用<代码>递增
/
递减
返回一个值。您甚至使用了返回值
Func
,如果编译了它,就可以执行此操作,但您仍然不能在该上下文中使用
ref

使用自定义委托类型,这很容易

delegate int InterlockedOp(ref int location);
即使编译了
Action
,它也不会工作<代码>递增/
递减
返回一个值。您甚至使用了返回值
Func
,如果编译了它,就可以执行此操作,但您仍然不能在该上下文中使用
ref

使用自定义委托类型,这很容易

delegate int InterlockedOp(ref int location);

如果没有内置,则必须创建自己的委托类型,请参见:没有内置,则必须创建自己的委托类型,请参见:是的,我错误地使用了
操作
,应该是
Func
。感谢您向一位代表展示如何做到这一点。现在开始学习使用委托和
Func
/
操作
:)是的,我错误地使用了
Action
,应该是
Func
。感谢您向一位代表展示如何做到这一点。现在开始学习使用委托和
Func
/
操作之间的区别:)