`
john2007
  • 浏览: 76153 次
  • 性别: 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研究资料,What Is ChatGPT Doing ... and Why Does It Work (Stephen Wolfram) (Z-Library)

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

    没有人预料到这一点——甚至包括它的创造者:ChatGPT作为一种能够以令人信服的人类水平进行写作的AI已经出现在舞台上。但是它真正的工作原理是什么?其“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...

    Thinking In C# ( 英文版,PDF)

    Why? Because it's different from any other language. C# comes from C++ and Java in some extend views. So it's obviouse for C# that it have the two important advantages of C++ and Java. It's easy to ...

    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 ...

    why does software cost so much

    这是一篇经典的文章,把软件开发过程中存在的问题说的面面俱到,很值得从事软件开发行业的相关人员读一读!

    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 ...

    The_Book_of_Why__The_New_Science_of_Cause_and_Effect.mobi

    A pioneer of artificial intelligence shows how the study of causality ... And just as Pearl's discoveries have enabled machines to think better, The Book of Why explains how we can think better.

    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 ...

    Apress A Programmers Guide to C# 5.0 4th Edition 201211

    purpose programming language, each fast-paced, focused chapter will take you straight to the heart of a feature of C# and show you why it works the way it does. Written by one-time C# Test Lead, ...

    C# 6.0 in a Nutshell.pdf

    When you have questions about C# 6.0 or the .NET CLR and its core Framework assemblies, this bestselling guide has the answers you need. C# has become a language of unusual flexibility and breadth ...

    Pro C# 7, 8th Edition

    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...

    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....

    c# ASP.MVC websocket在线聊天

    C# MVCwebsocket在线聊天。项目使用Asp.net MVC技术结合websocket技术开发。

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

    (1) Construct the precedence graph for S. (2) Is S a serializable schedule (3) I

    The C# Programmer's Study Guide (MCSD): Exam: 70-483

    The “What, Why, and How” of each concept is presented along with quick summaries, code challenges, and exam questions to review and practice key concepts. You will learn how to use: Lambda ...

    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 ...

Global site tag (gtag.js) - Google Analytics