简体   繁体   English

如何声明与函数签名不同的新委托?

[英]How to declare a new delegate that differ from function signature?

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
}

I'm trying to have a generic function like aaa which is defined in code. 我正在尝试使用像代码中定义的aaa这样的泛型函数。
The first call should change b because it's passed as by-ref but the second call shouldn't change b because it's passed as by-val. 第一个调用应该更改b因为它是作为by-ref传递的,但是第二个调用不应该更改b因为它是作为by-val传递的。

You can't do it with delegates because the parameters of the delegates and aaa don't match. 您不能使用委托,因为委托和aaa的参数不匹配。
You can do something like this instead (create method adapters aaaRefInt and aaaInt ): 你可以做这样的事情(创建方法适配器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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM