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调用中的第一个参数(context)。有没有人看到这个问题或者对这个问题有一些建议?
这些双星号是警告的原因。我在编辑器上点击“粗体”,它就这样做了,所以我就去了。星号不在我的代码中。
答案 0 :(得分:6)
将ref
与代表一起使用是一个坏主意,IMO。 (说实话,我说这通常是一个坏主意。说实话。让你的方法做一件事并有一个结果。)
我认为它根本不起作用 - 但显然确实如此,只要您在拨打ref
时提供EndInvoke
参数:
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
的大部分用途都是由于不理解how parameter passing works in C# ......这可能就是这种情况吗?你真的需要第一个参数是ref
吗?您可以将代理的返回值改为新上下文吗?
答案 1 :(得分:5)
BeginInvoke
可能不期望那里有ref
参数。你说ref context
,即传递对该对象的引用(引用本身)。你能否确认BeginInvoke
的方法签名?
答案 2 :(得分:1)
我认为您并不完全了解ref
的工作原理。
首先,ref
(或out
)是方法签名的一部分,因此如果在方法中将参数指定为ref
参数,那么必须< / strong>使用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”。正常参数可以被认为只是“在”中(我正在组成术语“在”中)。