簡體   English   中英

c# 參數為 'ref' 而參數被聲明為 'value'

[英]c# Argument is 'ref' while parameter is declared as 'value'

public virtual IAsyncResult BeginProcessRequest(RequestContext context, AsyncCallback callback, object state)
{
    return this.process.BeginInvoke(**ref context**, callback, state);
}

public virtual RequestContext EndProcessRequest(IAsyncResult result)
{
    RequestContext context = null;
    this.process.EndInvoke(**ref context**, result);
    return context;
}

上述兩種方法在我的項目中引起了一些警告。 我不確定我是否理解他們。 警告是:

參數是 'ref' 而參數被聲明為 'value'

並且警告的位置是 Invoke 調用中的第一個參數(上下文)。 有沒有人認為這有什么問題或對這個問題有一些建議?

那些雙星號是警告的原因。 我在編輯器上點擊了“粗體”,它做到了,所以我就跟着它去了。 星號不在我的代碼中。

IMO,將ref與代表一起使用是個壞主意。 (老實說,我想說這通常是個壞主意。讓你的方法做一件事並產生一個結果。)

我認為它根本不起作用 - 但顯然它確實起作用,只要您在調用EndInvoke時也提供ref參數:

using System;

class Program
{
    delegate void Foo(ref int x, string y);

    static void SampleFoo(ref int x, string y)
    {
        Console.WriteLine("Incoming: {0}", x); // 10
        x = y.Length;
    }

    static void Main(string[] args)
    {
        int x = 0;
        int input = 10;
        Foo f = SampleFoo;
        IAsyncResult result = f.BeginInvoke(ref input, "Hello", null, null);
        f.EndInvoke(ref x, result);
        Console.WriteLine("Result: {0}", x); // 5
    }
}

這里的行為可能令人困惑......如果可能的話,我會避免它。

大多數使用ref是由於不了解參數傳遞在 C# 中的工作原理......這里有可能是這種情況嗎? 你真的需要第一個參數是ref嗎? 你能把委托的返回值改為新的上下文嗎?

BeginInvoke可能不希望那里有ref參數。 你說ref context ,即傳遞對 object 的引用(本身就是一個引用)。 你能確認BeginInvoke的方法簽名嗎?

我認為您並不完全了解ref的工作原理。

首先, ref (或out )是方法簽名的一部分,所以如果在方法中參數被指定為ref參數,那么你必須使用ref否則你不能使用ref

其次在:

public virtual IAsyncResult BeginProcessRequest(RequestContext context, AsyncCallback callback, object state)
{
    return this.process.BeginInvoke(ref context, callback, state);
}

ref沒有做任何事情,因為您沒有在任何地方使用context的新值。 ref就像一個out參數,只是它既是“in”又是“out”。 普通參數只能被認為是“in”(我正在編造術語“in”)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM