是否可以在C#内置Action <>委托中使用引用类型?
收藏

C# has built-in delegates Action<> and Func<>. Is it possible to use 'ref' type parameters for this delegates? For example, this code:

public delegate 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;

有什么提示吗?

最佳答案

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.

但是,您可以构建自己的一组等效类型,例如

delegate void ActionRef<T>(ref T item);

当然,如果您希望在同一委托中混合使用ref和non-ref参数,则会遇到一系列可怕的组合:

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);

    公众号
    关注公众号订阅更多技术干货!