C#的ref和out使用

ref和out是C#中用于参数传递的关键字,它们都允许在方法内部修改参数的值,区别如下:

1、ref关键字:使用ref关键字声明的参数,在方法调用前必须被初始化,并且可以被视为已经赋予了一个初始值。在方法内部对ref参数的修改会影响到方法外部传入的实参,也就是说,我在方法内部修改了局部的值,那么全员变量的值也会被修改

public class test : MonoBehaviour
{
    [SerializeField] int a;
    // Start is called before the first frame update
    void Start()
    {
        XiuGai(ref a);
    }

    // Update is called once per frame
    void XiuGai(ref int b)
    {
        b = 100;
    }
}

2、out关键字:使用out关键字声明的参数,在方法内部不需要被初始化,可视为未赋初始值。在方法内部必须对out参数进行赋值,否则会导致编译错误。与ref关键字不同,out参数可以在方法内部确定其值,也就是说方法内部必须对局部变量赋值

public class test : MonoBehaviour
{
    [SerializeField] int a;
    // Start is called before the first frame update
    void Start()
    {
        XiuGai(out a);
    }

    void XiuGai2(out int b)
    {
        b = 50;
    }
}

  

3、总结:ref传的值在方法内部可以不修改其值,out则必须修改

4、这个可以用在任务管理器,或者需要实时更新的参数上,用途还是很大的

猜你喜欢

转载自blog.csdn.net/k253316/article/details/131800602
今日推荐