[英]Is it possible to use ref types in C# built-in Action<> delegate?
C#內置了委托Action<>
和Func<>
。 是否可以為此代表使用'ref'類型參數? 例如,這段代碼:
public delegate void DTest( ref Guid a );
public event DTest ETest;
會編譯。 但是如果我使用Action<>
,它將無法編譯:
public event Action< ref Guid > ETest;
任何提示?
不,您不能對Action
委托使用pass-by-reference。 雖然在框架中存在“通過引用傳遞的Type
”作為Type
的概念,但就C#而言,它並不是正常意義上的類型。 如果您看到我的意思, ref
是參數的修飾符,而不是類型名稱的一部分。
但是,您可以構建自己的等效類型集,例如
delegate void ActionRef<T>(ref T item);
當然,如果你想在同一個委托中混合使用ref和非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);
只要您的引用是復雜對象(具有屬性),您就可以。
示例對象:
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; }
}
用於動作:
Action<MyComplexObject> myAction = (MyComplexObject result) =>
{
result.Value = MyMethodThatReturnsSomething();
};
由於未更改MyComplexObject引用,因此將保留數據。
也發布在我的博客上 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.