开发者

Optional Output Parameters [duplicate]

This question already has answers here: 开发者_Go百科 C# 4.0 optional out/ref arguments (11 answers) Closed 9 years ago.

In C# 4, is there a good way to have an optional output parameter?


Not really, though you can always overload the method with another one that does not take the output parameter.


No.

To make it "optional", in the sense that you don't need to assign a value in the method, you can use ref.


Decorating the parameters with OptionalAttribute doesn't work, either. To extend the previous sample, you'd get something like:

private void Func(
    [Optional] out int optional1, 
    [Optional] out string optional2) 
{ /* ... */ }

Note that the above will compile (perhaps unfortunately). However, attempting to compile:

Func(out i);

will fail unless an overload with a one-parameter signature is explicitly provided.

To (theoretically) make the above work is a significant problem. When a method with an omitted optional parameter is called, a stack frame containing the values of all the parameters is created, and the missing value(s) are simply filled with the specified default values.

However, an "out" parameter is a reference, not a value. If that parameter is optional and not supplied, what variable would it reference? The compiler still needs to enforce the requirement that the "out" parameter be filled before any normal return from the method, as the compiler doesn't know a priori which (if any) optional parameters are specified by a caller. This means that a reference to dummy variable somewhere would have to be passed so the method has something to fill. Managing this dummy variable space would create a nasty headache for the writer of the compiler. I'm not saying that it would be impossible to work out the details of how this would work, but the architectural implications are great enough that Microsoft understandably passed on this feature.


private object[] Func();

assign as many as optional outputs you want in return object array and then use them! but if you mean optional output something like

private void Func(out int optional1, out string optional2)

and then you call something like

Func(out i);

then the answer is no you cant. also C# and .NET framework hast many many data structures that are very flexible like List and Array and you can use them as an output parameter or as return type so there is no need to implement a way to have optional output parameters.


public class Dummy<T>
{
    public T Value;
}

Then use DoSomething(out new Dummy<int>().Value), where int could be of any type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜