Func / Action delegates with reference arguments/parameters or anonymous functions

我与影子孤独终老i 提交于 2019-12-01 01:47:39

问题


I just wondered, how the exact syntax is for ref and out parameters for delegates and inline lambda functions.

here is an example

if a function is defined as

 public void DoSomething(int withValue) { } 

a delegate in a function can be created by

 public void f()
 {   
     Action<int> f2 = DoSomething;
     f2(3);
 }

how is that syntax, if the original function would be defined as

 public void DoSomething(ref int withValue) { withValue = 3; } 

回答1:


You need to define a new delegate type for this method signature:

delegate void RefAction<in T>(ref T obj);

public void F()
{
    RefAction<int> f2 = DoSomething;
    int x = 0;
    f2(ref x);
}

The reason why the .NET Framework does not include this type is probably because ref parameters are not very common, and the number of needed types explodes if you add one delegate type for each possible combination.




回答2:


You can't use Action, Func<T>, or the built-in delegates, but need to define your own in this case:

delegate void ActionByRef<T>(ref T value);

Then, given this, you can have:

int value = 3;
ActionByRef<int> f2 = DoSomething;
f2(ref value);


来源:https://stackoverflow.com/questions/13923685/func-action-delegates-with-reference-arguments-parameters-or-anonymous-functio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!