zoukankan      html  css  js  c++  java
  • What's the difference between the 'ref' and 'out' keywords?

    What's the difference between the 'ref' and 'out' keywords?

    You: I need to pass an object so that it can be modified It looks like MyClass would be a class type, i.e. a reference type. In that case, the object you pass can be modified by the myFunction even with no ref/out keyword. myFunction will receive a new reference that points to the same object, and it can modify that same object as much as it wants. The difference the ref keyword would make, would be that myFunction received the same reference to the same object. That would be important only if myFunction were to change the reference to point to another object.

    回答1

    ref tells the compiler that the object is initialized before entering the function, while out tells the compiler that the object will be initialized inside the function.

    So while ref is two-ways, out is out-only.

    回答2

    The ref modifier means that:

    1. The value is already set and
    2. The method can read and modify it.

    The out modifier means that:

    1. The Value isn't set and can't be read by the method until it is set.   就算在进入方法前,设置了值,也是无效的
    2. The method must set it before returning.                                   

    This answer most clearly and concisely简洁地 explains the restrictions that the compiler imposes when using the out keyword as opposed to the ref keyword.

    Is using the 'ref' keyword for string parameters in methods good for performance in C#? [duplicate]

    When I use this method, the compiler creates a copy of the text for the method, right?

    No, it doesn't. string is a reference type, and the compiler will create a new stack variable which points to the same string represented at a given memory address. It won't copy the string.

    When you use ref on a reference type, there won't be a copy of the pointer to the string created. It will simply pass the already created reference. This is useful only when you want to create an entirely new string:

    void Main()
    {
        string s = "hello";
        M(s);
        Console.WriteLine(s);
        M(ref s);
        Console.WriteLine(s);
    }
    
    public void M(string s)
    {
        s = "this won't change the original string";
    }
    
    public void M(ref string s)
    {
        s = "this will change the original string";
    }

    So is it good for performance using ref like this?

    The performance gains won't be noticeable. What will happen is other developers getting confused as to why you used ref to pass the string.

  • 相关阅读:
    英文字典。怎样设计数据结构
    最近看的几部电影电视剧
    pylucene 中文
    提高浏览体验的五十个最佳FireFox扩展插件
    结构和细节
    <传> 《程序猿装B指南》,程序员童鞋们请认真学习
    c++ builder TTreeView customSort 实现 自定义排序
    《转》c++ 字符串系列:字符编码进阶(下)
    庆祝我又读完一本书
    c++ 回调函数深究
  • 原文地址:https://www.cnblogs.com/chucklu/p/13152548.html
Copyright © 2011-2022 走看看