2016-02-29 37 views
0

要求:我應該使用什麼參數修改關鍵字?

  1. 變量不需要經過時入函數進行分配。 (與參考不同)
  2. 變量不需要在函數中分配。 (不同於)

現在,我將在下面的代碼中調用關鍵字mykw。

public class MyObj{ 
    int myInt; 
    public void setMyInt(int val){ 
     myInt = val; 
    } 
} 
public class MyObjContainer{ 
    private MyObj myObj; 
    //this function is the only way the user is allowed to get myObj. 
    //it returns whether myObj isn't null 
    //this is to disencourage programmers from using myObj without checking if myObj is null 
    public bool tryGetMyObj(mykw MyObj tryget){ 
     if(myObj != null){ 
      tryget= myObj; 
      return true; 
     } 
     //Micro optimization here: no needless processing time used to assign a value to tryget 
     return false; 
    } 
} 
public class MyScript { 
    public MyObjContainer[] myObjContainerList; 
    public void foo(){ 
     foreach(MyObjContainer myObjContainer in myObjContainerList){ 
      MyObj tryget; //Micro optimization here: no needless processing time used to assign a value to tryget 
      if(myObjContainer.tryGetMyObj(mykw tryget)){ 
       tryget.setMyInt(0); 
      } 
      //else ignore 
      //if uses tries accessing tryget.myInt here, I expect C# compiler to be smart enough to find out that tryget isn't assigned and give a compile error 
     } 
    } 
} 

對於上面的代碼,使用出或代替mykw給我一個錯誤。

回答

0

如果使用ref,那麼你需要初始化在調用的參數:

public bool tryGetMyObj(ref MyObj tryget) { ... } 

MyObj tryget = null; 
if(myObjContainer.tryGetMyObj(ref tryget) { ... } 

如果使用out那麼被叫方必須在每個路徑初始化值:

public bool tryGetMyObj(out MyObj tryget) { 
    if(myObj != null){ 
     tryget= myObj; 
     return true; 
    } 
    tryget = null; 
    return false; 
} 

MyObj tryget; 
if(myObjContainer.tryGetMyObj(out tryget)){ ... } 
+0

我想關鍵字符合要求1和要求2.我已經把原因放在我提供的代碼片段的評論中。 –

+0

@RyanAWE - 沒有這樣的修飾符,所以你必須使用'ref'或'out'如圖所示。無論如何,我不確定它們會比你要找的方法慢。 – Lee

+0

有沒有辦法讓我創建一個函數爲mykw的參數修飾符,以便我可以使用它? –

相關問題