我正在試驗DynamicObject
。我試圖做的事情之一是設置參數值ref
/out
,如下面的代碼所示。但是,我無法正確設置i
和j
的值Main()
(即使它們在TryInvokeMember()
中設置正確)。有誰知道如何用ref
/out
參數調用DynamicObject
對象,並且能夠檢索方法內設置的值?C#4.0'動態'不設置參考/輸出參數
class Program
{
static void Main(string[] args)
{
dynamic proxy = new Proxy(new Target());
int i = 10;
int j = 20;
proxy.Wrap(ref i, ref j);
Console.WriteLine(i + ":" + j); // Print "10:20" while expect "20:10"
}
}
class Proxy : DynamicObject
{
private readonly Target target;
public Proxy(Target target)
{
this.target = target;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
int i = (int) args[0];
int j = (int) args[1];
target.Swap(ref i, ref j);
args[0] = i;
args[1] = j;
result = null;
return true;
}
}
class Target
{
public void Swap(ref int i, ref int j)
{
int tmp = i;
i = j;
j = tmp;
}
}
更新7/15: 微軟聲稱已經解決了這一問題,爲下一個版本的.NET http://connect.microsoft.com/VisualStudio/feedback/details/543101/net-4-0s-dynamicobject-doesn-t-set-ref-out-arguments
更新2012年9月8日: 用VS.NET 2012測試與.NET 4.0和4.5,確認:它已經修復。
完全重複:http:// stackoverflow。com/questions/2268857/c-4-determining-parameter-passing-semantics-in-dynamic-calls – Gabe 2010-03-19 06:21:00
@gabe:實際上我看到了這個問題,但是問題是關於是否可以知道一個參數是否可以被稱爲通過ref/out或不通過,這與我在這裏要求的完全不同。我對此並不感興趣,因爲我可以對「目標」類進行一些思考。 – 2010-03-19 06:27:43
儘管你的問題是不同的,那麼答案就包括你的問題的答案:* DynamicObject是「按值調用」* – Gabe 2010-03-19 07:16:59