![](/img/trans.png)
[英]Should I use ref when modifying the content of an object passed as a parameter
[英]What parameter modifying keyword should I use?
要求:
現在,我將在下面的代碼中調用關鍵字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.