我应该使用什么参数修改关键字

本文关键字:修改 关键字 参数 什么 我应该 | 更新日期: 2023-09-27 18:36:43

要求:

  1. 变量在传递到函数中时不需要赋值。(与参考不同)
  2. 变量
  3. 不需要在函数中赋值。(不像外面)

现在,我将在下面的代码中调用关键字 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)){ ... }