반환 값 또는 매개 변수 중 어느 것이 더 낫습니까?
메소드에서 값을 얻으려면 다음과 같이 리턴 값을 사용할 수 있습니다.
public int GetValue();
또는:
public void GetValue(out int x);
나는 그들 사이의 차이점을 실제로 이해하지 못하므로 어느 것이 더 좋은지 모릅니다. 설명 해줄 수 있습니까?
감사합니다.
메서드에 반환 할 다른 항목이없는 경우 반환 값은 거의 항상 올바른 선택입니다. (사실, 난 것 어떤 경우 생각할 수 없다 이제까지 보이드 방법을 원하는 out
나는 선택의 여지가있는 경우, 매개 변수입니다. 7의 C # Deconstruct
언어 지원 해체하는 방법이 규칙에 매우, 매우 드문 예외로 작용 .)
다른 것 외에도 호출자가 변수를 별도로 선언하지 않아도됩니다.
int foo;
GetValue(out foo);
vs
int foo = GetValue();
Out 값은 다음과 같이 메소드 체인을 방지합니다.
Console.WriteLine(GetValue().ToString("g"));
(실제로, 이는 속성 설정 기의 문제 중 하나이기도하며, 빌더 패턴이 빌더를 리턴하는 메소드를 사용하는 이유입니다 (예 :) myStringBuilder.Append(xxx).Append(yyy)
.
또한 출력 매개 변수는 리플렉션과 함께 사용하기가 약간 어렵고 일반적으로 테스트도 어렵게 만듭니다. (일반적으로 매개 변수보다 반환 값을 쉽게 조롱하기 위해 더 많은 노력을 기울입니다). 기본적으로 그들이 더 쉽게 만들 수 있다고 생각할 수있는 것은 없습니다 ...
반환 값 FTW.
편집 : 무슨 일인지에 관해서 ...
당신이 "밖으로"매개 변수에 인수를 전달하면 기본적으로, 이 변수에 전달합니다. (배열 요소도 변수로 분류됩니다.) 호출하는 메소드에는 매개 변수의 스택에 "새"변수가 없습니다. 변수에 저장을 위해 사용합니다. 변수의 모든 변경 사항이 즉시 표시됩니다. 차이점을 보여주는 예는 다음과 같습니다.
using System;
class Test
{
static int value;
static void ShowValue(string description)
{
Console.WriteLine(description + value);
}
static void Main()
{
Console.WriteLine("Return value test...");
value = 5;
value = ReturnValue();
ShowValue("Value after ReturnValue(): ");
value = 5;
Console.WriteLine("Out parameter test...");
OutParameter(out value);
ShowValue("Value after OutParameter(): ");
}
static int ReturnValue()
{
ShowValue("ReturnValue (pre): ");
int tmp = 10;
ShowValue("ReturnValue (post): ");
return tmp;
}
static void OutParameter(out int tmp)
{
ShowValue("OutParameter (pre): ");
tmp = 10;
ShowValue("OutParameter (post): ");
}
}
결과 :
Return value test...
ReturnValue (pre): 5
ReturnValue (post): 5
Value after ReturnValue(): 10
Out parameter test...
OutParameter (pre): 5
OutParameter (post): 10
Value after OutParameter(): 10
차이점은 "포스트"단계에서, 즉 로컬 변수 또는 매개 변수가 변경된 후입니다. ReturnValue 테스트에서는 정적 value
변수와 아무런 차이가 없습니다 . OutParameter 테스트에서 value
변수는 행에 의해 변경됩니다tmp = 10;
What's better, depends on your particular situation. One of the reasons out
exists is to facilitate returning multiple values from one method call:
public int ReturnMultiple(int input, out int output1, out int output2)
{
output1 = input + 1;
output2 = input + 2;
return input;
}
So one is not by definition better than the other. But usually you'd want to use a simple return, unless you have the above situation for example.
EDIT: This is a sample demonstrating one of the reasons that the keyword exists. The above is in no way to be considered a best practise.
You should generally prefer a return value over an out param. Out params are a neccissary evil if you find yourself writing code that needs to do 2 things. A good example of this is the Try pattern (such as Int32.TryParse).
Let's consider what the caller of your two methods would have to do. For the first example I can write this...
int foo = GetValue();
Notice that I can declare a variable and assign it via your method in one line. FOr the 2nd example it looks like this...
int foo;
GetValue(out foo);
I'm now forced to declare my variable up front and write my code over two lines.
update
A good place to look when asking these types of question is the .NET Framework Design Guidelines. If you have the book version then you can see the annotations by Anders Hejlsberg and others on this subject (page 184-185) but the online version is here...
http://msdn.microsoft.com/en-us/library/ms182131(VS.80).aspx
If you find yourself needing to return two things from an API then wrapping them up in a struct/class would be better than an out param.
There's one reason to use an out
param which has not already been mentioned: the calling method is obliged to receive it. If your method produces a value which the caller should not discard, making it an out
forces the caller to specifically accept it:
Method1(); // Return values can be discard quite easily, even accidentally
int resultCode;
Method2(out resultCode); // Out params are a little harder to ignore
Of course the caller can still ignore the value in an out
param, but you've called their attention to it.
This is a rare need; more often, you should use an exception for a genuine problem or return an object with state information for an "FYI", but there could be circumstances where this is important.
It's preference mainly
I prefer returns and if you have multiple returns you can wrap them in a Result DTO
public class Result{
public Person Person {get;set;}
public int Sum {get;set;}
}
You can only have one return value whereas you can have multiple out parameters.
You only need to consider out parameters in those cases.
However, if you need to return more than one parameter from your method, you probably want to look at what you're returning from an OO approach and consider if you're better off return an object or a struct with these parameters. Therefore you're back to a return value again.
You should almost always use a return value. 'out
' parameters create a bit of friction to a lot of APIs, compositionality, etc.
The most noteworthy exception that springs to mind is when you want to return multiple values (.Net Framework doesn't have tuples until 4.0), such as with the TryParse
pattern.
I would prefer the following instead of either of those in this simple example.
public int Value
{
get;
private set;
}
But, they are all very much the same. Usually, one would only use 'out' if they need to pass multiple values back from the method. If you want to send a value in and out of the method, one would choose 'ref'. My method is best, if you are only returning a value, but if you want to pass a parameter and get a value back one would likely choose your first choice.
Both of them have a different purpose and are not treated the same by the compiler. If your method needs to return a value, then you must use return. Out is used where your method needs to return multiple values.
If you use return, then the data is first written to the methods stack and then in the calling method's. While in case of out, it is directly written to the calling methods stack. Not sure if there are any more differences.
There is no real difference , out parameters are in C# to allow method return more then one value , thats all.
However There are some slight differences , but non of them are realy important:
Using out parameter will enforce you to use two lines like:
int n;
GetValue(n);
while using return value will let you do it in one line:
int n = GetValue();
Another difference (correct only for value types and only if C# doesn't inline the function) is that using return value will necessarily make a copy of the value when the function return while using OUT parameter will not necessarily do so.
As others have said: return value, not out param.
May I recommend to you the book "Framework Design Guidelines" (2nd ed)? Pages 184-185 cover the reasons for avoiding out params. The whole book will steer you in the right direction on all sorts of .NET coding issues.
Allied with Framework Design Guidelines is the use of the static analysis tool, FxCop. You'll find this on Microsoft's sites as a free download. Run this on your compiled code and see what it says. If it complains about hundreds and hundreds of things... don't panic! Look calmly and carefully at what it says about each and every case. Don't rush to fix things ASAP. Learn from what it is telling you. You will be put on the road to mastery.
I think one of the few scenarios where it would be useful would be when working with unmanaged memory, and you want to make it obvious that the "returned" value should be disposed of manually, rather than expecting it to be disposed of on its own.
Additionally, return values are compatible with asynchronous design paradigms.
You cannot designate a function "async" if it uses ref or out parameters.
In summary, Return Values allow method chaining, cleaner syntax (by eliminating the necessity for the caller to declare additional variables), and allow for asynchronous designs without the need for substantial modification in the future.
Using the out keyword with a return type of bool, can sometimes reduce code bloat and increase readability. (Primarily when the extra info in the out param is often ignored.) For instance:
var result = DoThing();
if (result.Success)
{
result = DoOtherThing()
if (result.Success)
{
result = DoFinalThing()
if (result.Success)
{
success = true;
}
}
}
vs:
var result;
if (DoThing(out result))
{
if (DoOtherThing(out result))
{
if (DoFinalThing(out result))
{
success = true;
}
}
}
out is more useful when you are trying to return an object that you declare in the method.
Example
public BookList Find(string key)
{
BookList book; //BookList is a model class
_books.TryGetValue(key, out book) //_books is a concurrent dictionary
//TryGetValue gets an item with matching key and returns it into book.
return book;
}
return value is the normal value which is returned by your method.
Where as out parameter, well out and ref are 2 key words of C# they allow to pass variables as reference.
The big difference between ref and out is, ref should be initialised before and out don't
I suspect I'm not going to get a look-in on this question, but I am a very experienced programmer, and I hope some of the more open-minded readers will pay attention.
I believe that it suits object-oriented programming languages better for their value-returning procedures (VRPs) to be deterministic and pure.
'VRP' is the modern academic name for a function that is called as part of an expression, and has a return value that notionally replaces the call during evaluation of the expression. E.g. in a statement such as x = 1 + f(y)
the function f
is serving as a VRP.
'Deterministic' means that the result of the function depends only on the values of its parameters. If you call it again with the same parameter values, you are certain to get the same result.
'Pure' means no side-effects: calling the function does nothing except computing the result. This can be interpreted to mean no important side-effects, in practice, so if the VRP outputs a debugging message every time it is called, for example, that can probably be ignored.
Thus, if, in C#, your function is not deterministic and pure, I say you should make it a void
function (in other words, not a VRP), and any value it needs to return should be returned in either an out
or a ref
parameter.
For example, if you have a function to delete some rows from a database table, and you want it to return the number of rows it deleted, you should declare it something like this:
public void DeleteBasketItems(BasketItemCategory category, out int count);
If you sometimes want to call this function but not get the count
, you could always declare an overloading.
You might want to know why this style suits object-oriented programming better. Broadly, it fits into a style of programming that could be (a little imprecisely) termed 'procedural programming', and it is a procedural programming style that fits object-oriented programming better.
Why? The classical model of objects is that they have properties (aka attributes), and you interrogate and manipulate the object (mainly) through reading and updating those properties. A procedural programming style tends to make it easier to do this, because you can execute arbitrary code in between operations that get and set properties.
The downside of procedural programming is that, because you can execute arbitrary code all over the place, you can get some very obtuse and bug-vulnerable interactions via global variables and side-effects.
So, quite simply, it is good practice to signal to someone reading your code that a function could have side-effects by making it non-value returning.
참고URL : https://stackoverflow.com/questions/810797/which-is-better-return-value-or-out-parameter
'development' 카테고리의 다른 글
java.exe와 javaw.exe의 차이점 (0) | 2020.06.21 |
---|---|
약어의 의미 std :: string (0) | 2020.06.21 |
파이썬 : iterable의 내용을 세트에 추가하는 방법? (0) | 2020.06.21 |
Objective-C 용 JSON 구문 분석기 (JSON 프레임 워크, YAJL, TouchJSON 등) 비교 (0) | 2020.06.20 |
감사 로깅을위한 데이터베이스 디자인 (0) | 2020.06.20 |