2013-05-02 68 views
0

我有一組從一個BaseObject繼承的對象,它們具有一些全局原始屬性(索引等)。現在,我有兩個對象,其中一個對象(目標對象)僅具有基本屬性的值,另一個對象(源對象之一)具有所有其他屬性的值(從第3個第三方應用程序),但基礎的。某些更新從方法中丟棄

我試圖將所有源對象的屬性複製到目標對象,但保留目標的基本屬性的值。換句話說 - 我試圖在不刪除任何東西的情況下等於兩個對象的屬性值... target = source;只會刪除目標的基指數... 所以,我做它獲取作爲參數的兩個對象(鑄造到BaseObject)的方法和目標的指標的值複製到源以前生產的副本,就像這樣:

Public void Copy(BaseObject source, BaseObject target) 
{ 
    //Copy all primitive indexes here... 
    source.index = target.index; 
    source.reference = target.reference; 
    etc… 

    //Copy the updated object to the target one...  
    target = source; 
} 

在方法內部的調試模式下它似乎沒問題,但是 - 當我的代碼退出該方法時,我驚訝地發現儘管源對象已經同時被繼承和非繼承屬性更新,但目標值仍然保持不變。 所以,我不得不再次複製(更新)源到目標的方法外,像這樣:

InheritedObject sourceObj = CreateObjectWithPrimitiveIndexes(); 
InheritedObject targetObj = GetObjectWithNoIndexesFrom3rdParty(); 

targetObj.Copy(source: sourceObj, target: targetObj); 

//The targetObject is not updated, so I have to re-copy it outside the Copy() method 
targetObj = sourceObj; 

有人可以解釋我爲什麼sourceObj被更新,因爲它被髮送到副本()方法通過引用,但目標obj的行爲就像它發送的val和它的所有更新都被忽略外的方法... ???

我是否可以使用'ref','out'關鍵詞我在方法簽名等?

回答

3

如果分配到方法的參數,對於分配是可見的來電,該參數必須具有ref(或out)改性劑。見ref (C# Reference)

實施例:

// doesn't do anything! 
void Copy(BaseObject target) 
{ 
    ... 
    target = Something; 
} 

// with ref, assignment is to the *same* variable as the caller gave 
void Copy(ref BaseObject target) 
{ 
    ... 
    target = Something; 
} 

ADDITION:

作爲鏈接我提供註釋:

不要混淆通過引用 傳遞參考類型的概念的概念

這兩個概念是「垂直」,如下表所示:

          |     | 
              | ByVal (neither | ByRef (ref or 
              | ref nor out):  | out keyword): 
              |     | 
--------------------------------------------+-------------------+---------------------- 
value type (struct, enum)     | entire object  | no copy, argument 
              | is COPIED   | must be a variable, 
              |     | same variable used 
--------------------------------------------+-------------------+---------------------- 
reference type (class, interface, delegate) | reference COPIED; | no copy, argument 
              | NEW reference to | must be a variable, 
              | same object  | same variable used 
--------------------------------------------+-------------------+---------------------- 

如果不使用可變結構,然後結構類型的變量永遠只能通過重新assignemnt改變,然後以下原則進行的拇指是值類型和引用類型有用:

您需要ref(或out)關鍵字當且僅當你的方法分配 (包括複方賦值如+=)到所討論的參數。

另請參閱What is the use of 「ref」 for reference-type variables in C#?