gpt4 book ai didi

c# - 如何声明一个不同于函数签名的新委托(delegate)?

转载 作者:行者123 更新时间:2023-11-30 13:00:21 26 4
gpt4 key购买 nike

delegate void EmptyBody(ref int first );
delegate void AnotherEmptyBody(int first );
delegate void AnotherEmptyBody1(int first, int second);

public void aaa(params object[] pars)
{
DoSpecifiedProcessing();

pars[0] = 11;
}

public bool OnInIt()
{
int b = 0;

b = 44;
var n = new EmptyBody(aaa);
n(ref b);
//b variable must be 11


b = 44;
var x = new AnotherEmptyBody(aaa);
x(b);
//b shoudn't be changed in this call, so it should be 44
}

我正在尝试使用代码中定义的通用函数,如 aaa
第一次调用应更改 b,因为它作为 by-ref 传递,但第二次调用不应更改 b,因为它作为 by-val 传递。

最佳答案

你不能用委托(delegate)来做,因为委托(delegate)的参数和aaa不匹配。
您可以改为执行类似的操作(创建方法适配器 aaaRefIntaaaInt):

public void aaaRefInt(ref int first)
{
object[] Args = new object[]{first};
aaa(Args);
first = (int)Args[0];
}

public void aaaInt(int first)
{
aaa(new object[]{first});
}

var n = new EmptyBody(aaaRefInt);
n(ref b);

var x = new AnotherEmptyBody(aaaInt);
x(b);

关于c# - 如何声明一个不同于函数签名的新委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22268992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com