`
john2007
  • 浏览: 78259 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Why does C# have both 'ref' and 'out'?

阅读更多

ref out 两种参数传递方式都允许调用者更改传递来的参数的值,两者之间的不同很小,但很重要。两者最重要的不同就是他们所修饰的参数的指定值的方式不同。

 

带有out参数的方法在被调用之前不需要为out参数指定值,但是,在方法返回之前必须为out参数指定值。很绕口啊,看个例子吧:

class OutExample
{
      // Splits a string containing a first and last name separated
      // by a space into two distinct strings, one containing the first name and one containing the last name

      static void SplitName(string fullName, out string firstName, out string lastName)
      {
            // NOTE: firstName and lastName have not been assigned to yet.  Their values cannot be used.
            int spaceIndex = fullName.IndexOf(' ');
            firstName = fullName.Substring(0, spaceIndex).Trim();
            lastName = fullName.Substring(spaceIndex).Trim();
      }

      static void Main()
      {
            string fullName = "Yuan Sha";
            string firstName;
            string lastName;

            // NOTE: firstName and lastName have not been assigned yet.  Their values may not be used.
            SplitName(fullName, out firstName, out lastName);
            // NOTE: firstName and lastName have been assigned, because the out parameter passing mode guarantees it.

            System.Console.WriteLine("First Name '{0}'. Last Name '{1}'", firstName, lastName);
      }
}

 

可以把out参数看成是方法的另外的返回值。当一个方法要返回多个函数值时out是非常有用的。

 

我觉得ref更像引用,使用之前必须初始化。ref修饰的参数在方法内部修改后会反映在方法外部。因为他是引用传递:

 

class RefExample
{
      static object FindNext(object value, object[] data, ref int index)
      {
            // NOTE: index can be used here because it is a ref parameter
            while (index < data.Length)
            {
                  if (data[index].Equals(value))
                  {
                        return data[index];
                  }
                   index += 1;
            }
             return null;
      }

      static void Main()
      {
            object[] data = new object[] {1,2,3,4,2,3,4,5,3};

            int index = 0;
            // NOTE: must assign to index before passing it as a ref parameter
            while (FindNext(3, data, ref index) != null)
            {
                  // NOTE: that FindNext may have modified the value of index
                  System.Console.WriteLine("Found at index {0}", index);
                  index += 1;
            }

            System.Console.WriteLine("Done Find");
      }
}

 

 

分享到:
评论
5 楼 ray_linn 2009-03-04  
有什么难的?

ref的值在方法内部可能被使用,因此可能需要被赋值,也可以被修改,可以看成是"in out"

out只是用来返回值的,通常该方法需要返回多个值,比如buffer, buffersize, requiresize...
4 楼 小龟爬爬 2009-03-03  
ref使用之前必须初始化,而 out 只需要定义,不用初始化,但在方法返回之前必须为out参数指定值
3 楼 john2007 2008-12-29  
带有out参数的方法在被调用之前不需要为out参数指定值,但是,在方法返回之前必须为out参数指定值。
2 楼 feilng 2008-12-28  
out就是我保证out一个结果
ref就是我只是ref,不保证out
1 楼 seen 2008-12-23  
没看懂。。。这两者区别在哪?

相关推荐

    What Is ChatGPT Doing ... and Why Does It Work.pdf

    《ChatGPT在做什么...以及为什么它有效》 这本书由斯蒂芬·沃尔夫勒姆(Stephen Wolfram)撰写,探讨了ChatGPT的工作原理及其为何能成功运作。沃尔夫勒姆是计算科学领域的权威,他的公司Wolfram Media出版了这本书...

    What Is ChatGPT Doing ... and Why Does It Work(2023)

    《ChatGPT是如何工作的...以及为何它有效(2023)》这本书深入浅出地探讨了人工智能领域的一项新突破——ChatGPT的工作原理。ChatGPT是一个能够以人类水平生成自然语言的AI系统,其出现让业界大为震惊,甚至连它的创建...

    Pro C# 7: With .NET and .NET Core

    Dive in and discover why Pro C# has been a favorite of C# developers worldwide for over 15 years. Gain a solid foundation in object-oriented development techniques, attributes and reflection, generics...

    why does software cost so much

    【软件开发的代价】——为什么软件成本如此高昂 在信息技术领域,软件开发是核心环节,但为何软件开发的成本会让人觉得如此之高呢?这个问题在业内已经引发了广泛的讨论。著名作者和顾问杰里·韦因伯格(Jerry ...

    C# 2010捷径教程

    C# 2010 offers powerful new features, and this book is the fastest path to mastering them—and the rest of C#—for both experienced C# programmers moving to C# 2010 and programmers moving to C# from ...

    Effective C# 2ed (Covers C# 4.0)

    C# has matured over the past decade: It’s now a rich language with generics, functional programming concepts, and support for both static and dynamic typing. This palette of techniques provides great...

    C# 7.0 in A Nutshell

    When you have questions about C# 7.0 or the .NET CLR and its core Framework assemblies, this bestselling guide has the answers you need. Since its debut in 2000, C# has become a language of unusual ...

    Pro Windows 8.1 Development with XAML and C#

    What Metro and WinRT are capable of and why they are special Ways to use advanced features to create immersive and engaging Windows 8.1 applications How to create applications that work seamlessly ...

    Accelerated C# 2010

    C# 2010 offers powerful new features, and this book is the fastest path to mastering them—and the rest of C#—for both experienced C# programmers moving to C# 2010 and programmers moving to C# from ...

    Accelerated C# 2008

    but if you don't have the time to read 1200 pages, Accelerated C# 2008 gives you everything you need to know about C# 2008 in a concentrated 500 pages of must-know information and best practices....

    江西省丰城三中2020届九年级英语3月月考试题(无答案).doc

    - 个人习惯的描述:女士午餐通常吃什么(What does the woman usually have for lunch?)。 - 国家与文化的了解:女士来自哪个国家(Where is the woman from?),她喜欢中国的什么(What does the woman like ...

    c# ASP.MVC websocket在线聊天

    本项目是基于C#的ASP.NET MVC框架,结合WebSocket技术实现的一款在线聊天应用。WebSocket协议是一种在客户端和服务器之间建立长连接的协议,它允许双方进行实时、双向的数据传输,非常适合用于构建实时通信应用,如...

    2014小升初英语专题句型转换对划线部分提问.doc

    21. Does Jim have any story-books? 22. Does the old man do morning exercises every morning? 23. Are we from China? 特殊疑问句则是通过疑问词来引导,询问具体的信息,而不是简单地确认事实。以下是特殊疑问...

    数据库系统原理(英文)-16-DBS事务管理例题-v2-202012061

    【数据库事务管理】\n\n在数据库系统中,事务管理是确保数据一致性、并发控制和恢复机制的关键组成部分。本文将探讨一个并发事务的例子,以及如何分析其调度特性。\n\n首先,我们关注并发事务T1、T2、T3和T4在日程S...

    Multithreading with C# Cookbook(PACKT,2ed,2016)

    Multi-core processors are synonymous with computing speed and power in today’s world, which is why multithreading has become a key concern for C# developers. Multithreaded code helps you create ...

    C#.net笔试面试题集合

    29. Do you typically achieve what you set out to do? a) 你总是能实现自己为自己设定的目标吗? Miscellaneous Questions: 30. What de-motivates or discourages you? a) 有哪些因素可能会让你失去动力或...

Global site tag (gtag.js) - Google Analytics