Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use method parameters in C #

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

小编给大家分享一下C#中方法参数怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

C#方法参数

因方法要处理更改数值,你多多少少要传递值给方法,并从方法获得返回值。以下三个部分涉及到C#方法参数的三种参数。

◆输入参数

◆引用参数

◆输出参数

1.输入参数

你早已在例子中见过的一个参数就是输入参数。你用一个输入参数通过值传递一个变量给一个方法--方法的变量被调用者传递进来的值的一个拷贝初始化。示范输入参数的使用。

using System; public class SquareSample { public int CalcSquare(int nSideLength) { return nSideLength*nSideLength; } } class SquareApp { public static void Main() { SquareSample sq = new SquareSample(); Console.WriteLine(sq.CalcSquare(25)。ToString()); } }

输入参数按C/C++程序员早已习惯的工作方式工作。如果你来自VB,请注意没有能被编译器处理的隐式ByVal或ByRef--如果没有设定,参数总是用值传递。

这点似乎与我前面所陈述的有冲突:对于一些变量类型,用值传递实际上意味着用引用传递。迷惑吗? 一点背景知识也不需要:COM中的东西就是接口,每一个类可以拥有一个或多个接口。一个接口只不过是一组函数指针,它不包含数据。

重复该数组会浪费很多内存资源;所以,仅开始地址被拷贝给方法,它作为调用者,仍然指向接口的相同指针。那就是为什么对象用值传递一个引用。

2.引用参数

尽管可以利用输入参数和返回值建立很多方法,但你一想到要传递值并原地修改它(也就是在相同的内存位置),就没有那么好运了。这里用引用参数就很方便。

因为你传递了一个变量给该方法(不仅仅是它的值),变量必须被初始化。否则,编译器会报警。显示如何用一个引用参数建立一个方法。

// class SquareSample using System; public class SquareSample { public void CalcSquare(ref int nOne4All) { nOne4All *= nOne4All; } } class SquareApp { public static void Main() { SquareSample sq = new SquareSample(); int nSquaredRef = 20; // 一定要初始化 sq.CalcSquare(ref nSquaredRef); Console.WriteLine(nSquaredRef.ToString()); } }

正如所看到的,所有你要做的就是给定义和调用都加上ref限定符。因为变量通过引用传递,你可以用它来计算出结果

并传回该结果。但是,在现实的应用程序中,我强烈建议要用两个变量,一个输入参数和一个引用参数。

3.输出参数

传递参数的第三种选择就是把它设作一个输出参数。正如该名字所暗示,一个输出参数仅用于从方法传递回一个结果。它和引用参数的另一个区别在于:调用者不必先初始化变量才调用方法。

using System; public class SquareSample { public void CalcSquare(int nSideLength, out int nSquared) { nSquared = nSideLength * nSideLength; } } class SquareApp { public static void Main() { SquareSample sq = new SquareSample(); int nSquared; // 不必初始化 sq.CalcSquare(15, out nSquared); Console.WriteLine(nSquared.ToString()); } }以上是"C#中方法参数怎么用"这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report