了解C#對象引用和
呈現出獨特的情況。 讓我們澄清行為。 System.Drawing.Image
對像傳遞的細微差別>
>了解C#不直接傳遞對像是至關重要的。它將引用傳遞給對象。 對於參考類型,此參考由值複製。 這意味著一種方法接收參考的副本,而不是對象本身。 >
行為System.Drawing.Image
替換System.Drawing.Image
整個對象(例如,分配新圖像)都不會在方法之外反映。 這是因為該方法正在使用參考的副本。 重新分配該方法中的參考會創建一個新的參考,使原始的參考保持不變。 >
>通過價值與逐次傳遞
c#中的默認行為是兩個值類型和參考類型的逐個價值。 但是,您可以明確使用或ref
的關鍵字來強制通過參考。 out
>
>通過逐值(默認值):
>通過逐次參考(/ref
):out
演示了差異。 第一個版本不會改變原始圖像。第二個確實如此。但是,
<code class="language-csharp">public void ModifyImage(Image image) // Pass-by-Value { // This reassigns the reference, NOT modifying the original. image = Image.FromFile("newImage.jpg"); } public void ModifyImage(ref Image image) // Pass-by-Reference { // This reassigns the reference, modifying the original. image = Image.FromFile("newImage.jpg"); } public void ManipulateImage(Image image) // Pass-by-Value { // This modifies the *contents* of the original image. image.RotateFlip(RotateFlipType.Rotate90FlipNone); }</code>表明,圖像的
屬性(如旋轉)ModifyImage
> do ManipulateImage
會影響原始,因為它正在更改對象的內部狀態,而不是參考本身,因此會影響原始。 關鍵區別在於替換整個對象而不是修改其屬性。
以上是為什麼更改為system.drawing.image對像傳遞給C#方法並不總是持續存在?的詳細內容。更多資訊請關注PHP中文網其他相關文章!