开发者

C# Func(T) not accepting ref type input parameter

Can Func<...> accept arguments passed by reference in C#?

static void Main()
{
    Func<string,int, int> method = Work;
    method.BeginInvok开发者_开发百科e("test",0, Done, method);
    // ...
    //
}
static int Work(ref string s,int a) { return s.Length; }
static void Done(IAsyncResult cookie)
{
    var target = (Func<string, int>)cookie.AsyncState;
    int result = target.EndInvoke(cookie);
    Console.WriteLine("String length is: " + result);
}

I am not able define a Func<...> which can accept the ref input parameter.


The Func<T> delegates cannot take ref parameters.
You need to create your own delegate type which takes ref parameters.

However, you shouldn't be using ref here in the first place.


Expanding on SLaks answers.

The Func<T> family of delegates are generic and allow you to customize the type of the arguments and returns. While ref contributes to C#`s type system it's not actually a type at the CLR level: it's a storage location modifier. Hence it's not possible to use a generic instantiation to control whether or not a particular location is ref or not.

If this was possible it would be very easy to produce completely invalid code. Consider the following

T Method<T>() {
  T local = ...;
  ...
  return local;
}

Now consider what happens if the developer called Method<ref int>(). It would produce both a local and return value which are ref. This would result in invalid C# code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜