我应该使用哪些参数修改关键字?

时间:2016-02-29 05:18:46

标签: c# variables parameters out ref

要求:

  1. 将函数传递给函数时不需要赋值变量。 (与ref不同)
  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会给我一个错误。

1 个答案:

答案 0 :(得分: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)){ ... }