2015-05-04 41 views
0

我有一類Fruit,有很多的變量:mass, taste ...等 我有一類Apple有幾個變量添加到它:size, texture ......等等。承載座級的數據throught父類

我寫了一個簡單的函數來加載Fruit變量,並且不想複製它的全部來填充Apple變量。

public void ReadFruitData(string Name, ref Fruit newFruit);

public void ReadAppleData(string Name, ref Apple newApple);

我想打電話給ReadFruitDataReadAppleData,但不太清楚如何做到這一點,因爲我無法通過newApplenewFruit

class Apple : Fruit

任何想法我怎麼能做到這一點?

+2

爲什麼'ref'爲什麼不能老是你通過蘋果'ReadFruitData'? – Carsten

回答

4

內ReadAppleData使用一個臨時變量來做到這一點:

Fruit TempFruit = (Fruit)newApple; 
ReadFruitData(Name, ref TempFruit); 
// carry on with the rest of your code 

注:這是如果你試圖直接發送newApple,那麼這個討厭的編譯器會抱怨The best overloaded method match for... has some invalid arguments
它不適合任何情況。

由於在評論中提到,如果ReadFruitData分配的Fruit新實例裁判參數Patrick Hofman,這是不是你的解決方案。 (在這種情況下,您應該使用out而不是ref)。

這裏是when not to use this一個例子,你不需要ref關鍵字when you can use it.

+1

這打破了'ref'。 –

+0

@PatrickHofman不,它不。嘗試一下。 –

+0

它引用'TempFruit',而不是'newApple'。 –

-3

修改的 ReadFruitData你的函數定義(字符串名稱,樓盤水果newFruit)到 ReadFruitData(字符串名稱,Ref對象newFruit)

而且你的方法裏面,做一個演員。

例如 ReadFruitData(string Name,ref Object newFruit) { Fruit myFruit = newFruit as Fruit; 或 Apple myApple = newFruit as Apple; }

希望這會有所幫助。 :)

+1

不,請不要在你不需要的時候施放 - 施法與'null'幾乎一樣壞 – Carsten

+0

你的回答非常糟糕。你不應該添加依賴到調用方法只是爲了完成你自己的...(我建議刪除它) –

5

那麼,其實你可以。

如果您的Apple類繼承Fruit,您可以將派生類型的實例傳入該方法。實際的問題是使用ref關鍵字。試試寫出ref。如果您不需要,請不要使用它,或者使用返回值來返回新創建的實例。

如果你只是在newApple更新值,則可以省略ref和它的作品:

public void ReadFruitData(string Name, Fruit newFruit) 
{ } 

public void ReadAppleData(string Name, Apple newApple) 
{ 
    ReadFruitData(Name, newApple); 
} 
2

一個例子。

您正在使用參考類型。如果您修改這兩種方法中的FruitApple,則可以修改原始的FruitApple

如果您想通過intbool而不將其定義爲ref參數並且修改方法內的值,那麼原始變量的值不會更改。

參見:

+0

但是,您可以使用'ref'將引用設置爲引用類型。但總的來說,你是對的。 +1 –