何时使用return或void方法C# [英] When To user the return or void method C#

查看:237
本文介绍了何时使用return或void方法C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我目前正在学习C#,我想知道在哪种情况下我应该使用Void方法,何时应该使用return方法。

Hi,

I am currently learning C# and I want to know in which circumstances should i use a Void method and when should i use the return method.

推荐答案

我的建议是去阅读一些基础知识。 May ba book可以提供帮助。



My suggestion is to go and read some fundamentals. May b a book can help.

Quote:

用作返回类型对于方法,void指定该方法不返回值。

When used as the return type for a method, void specifies that the method doesn't return a value.



- MSDN [ ^ ]



因此,当您需要从当前方法返回到被调用方法时,请使用带有适当签名和值的return语句来返回如果您需要返回而不是使用 void



请查看以下教程以获得更多见解。

http://www.dotnetperls.com/return [ ^ ]



希望,它有帮助:)


--MSDN[^]

So, when you need something to be returned from your current method to the called method use a return statement with appropriate signature and value to return and if you need nohing to be returned than use void.

Check following tutorial to have some more insights.
http://www.dotnetperls.com/return[^]

Hope, it helps :)


使用 void 何时该方法没有告诉调用者,例如

Use void when the method has nothing to tell to the caller, e.g.
void ChangeColor(Color newColor);



你知道它不能失败(或者它可能只是抛出异常)。



每当需要将有意义的信息传递给调用者时,使用返回值的方法,例如


and you know it cannot fail (or it might just throw an exception).

Use a method returning a value, whenever you need to pass meaningful information to the caller, e.g.

bool IsRunning();


这是编程的第一步,



如果你想要一个要执行的表达式返回一个值,创建一个逻辑,编写一个函数并在你想要执行表达式的时候调用该函数。有了这个,您还将学习如何优化代码。这也有助于使用库中的功能。

返回函数示例,



This is the first step towards programming,

If you want a expression to be executed returning a value, create a logic, write a function and call the function as much time you want the expression to be executed. With this you will also learn how the code gets optimized. This also helps in using the function from a library.
Example for return function,

int Sum(int a, int b)
{
return (a+b);
}



使用main方法中的适当参数调用方法。


Call the method with appropriate parameters in main method.

Sum(5,3)
Sum(2,9)





在void方法中,你不返回一个值,只能用来显示一条消息。

例如: -





While in void method you don't return a value, and can use just to display a message.
Example:-

void DisplaySum(int a, int b)
{
Console.WriteLine("Sum of two numbers is="+a+b);
}





希望你从上面的例子中得到一些东西..



Hope you get something from the above examples..


这篇关于何时使用return或void方法C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆