簡體   English   中英

我應該使用什么參數修改關鍵字?

[英]What parameter modifying keyword should I use?

要求:

  1. 將變量傳遞給函數時,無需分配變量。 (與ref不同)
  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
        }
    }
}

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

如果使用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)){ ... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM