Is it possible to use ref types in C# built-in Action<> delegate?
C# has built-in delegates Action<>
and Func<>
. Is it possible to use 'ref' type parameters for this delegates? For example, this code:
public deleg开发者_JS百科ate void DTest( ref Guid a );
public event DTest ETest;
Will compile. But if I use Action<>
, it will not compile:
public event Action< ref Guid > ETest;
Any hints?
No, you can't use pass-by-reference with the Action
delegates. While there is a concept of "type passed by reference" as a Type
in the framework, it's not really a type in the normal sense as far as C# is concerned. ref
is a modifier for the parameter, not part of the type name, if you see what I mean.
However, you can build your own set of equivalent types, e.g.
delegate void ActionRef<T>(ref T item);
Of course, if you want a mixture of ref and non-ref parameters in the same delegate, you get into a horrible set of combinations:
delegate void ActionRef1<T1, T2>(ref T1 arg1, T2 arg2);
delegate void ActionRef2<T1, T2>(T1 arg1, ref T2 arg2);
delegate void ActionRef3<T1, T2>(ref T1 arg1, ref T2 arg2);
You can as long as your reference is a complex object (has properties).
Example object:
public class MyComplexObject
{
/// <summary>
/// Name provided for the result.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Value of the result.
/// </summary>
public object Value { get; set; }
}
Used in an Action:
Action<MyComplexObject> myAction = (MyComplexObject result) =>
{
result.Value = MyMethodThatReturnsSomething();
};
Since the MyComplexObject reference is not changed, the data is preserved.
Also posted on my blog.
精彩评论