2013-09-25 127 views
0

我想做的功能可以返回幾個原始數據類型來調用。原始數據類型的參考

我知道我可以返回第一個原語的函數結果,但如何返回函數參數中的原語?

public boolean myFunc(boolean outAnotherPrimitive) 
{ 
outAnotherPrimitive = true; //need to return value to caller 
return true; 
} 

只有這樣才能將原始圖像包裝到Object中,如Integer或Boolean?

+0

_return幾個原始數據types_你的意思是你想擁有一個具有許多原始的對象鍵入字段? –

+0

你想返回參數嗎? – arynaq

+1

您可以添加一些示例輸入和輸出函數嗎? – fvrghl

回答

1

只有這樣才能將原始圖像包裝到像Integer或Boolean這樣的對象中嗎?

根本不是,

我認爲它不是好的做法來轉換變量對象並獲取回用鑄造或instanceof之後。

  • 您可以使用接口作爲回調

例如:

OtherClass

MyClass的:

public class MyClass implements MyinterfaceItf { 

.... 

private void foo() 
{ 
    MyinterfaceItf itf = this; 

    myFunc(true, itf); 
} 

@override 
public void onFinish(bool, a){ 
    // here you can get your primitive data 
} 

} 

接口

public interface MyinterfaceItf{ 
public void onFinish(bool, a); 
} 
  • 其他選項,使用變量作爲全球

例如:

private boolean bool = false; 
private int num = 0; 


public boolean myFunc(boolean anotherPrimitive) 
{ 
bool = anotherPrimitive; 
num = 10; 
//.... 
} 
  • 下一個選項來創建新類,並用它來代替原語。

例如:

public class NewClass{ 
private boolean bool = false; 
private int num = 0; 
//... 

public void setBool(boolean flag){ 
    this.bool = flag; 
    } 
} 

public boolean myFunc(boolean anotherPrimitive, NewClass newClass) 
{ 
    return newClass.setBool(true); 
    } 

(我寫在本地編輯器,語法對不起)

+0

它的好處,但他可以使用其他方法:)像寫入文件和讀取它,寫入隊列/隊列,直接到內存:),順便說一句,你的變種更好,更容易,但問題是如此......,他希望在.NET中使用像ref這樣的輸入參數,哦:((( –