问题
I thought I understood limitations of ref returns as well as escaping scopes.
But now I found a case and I don't get why is it illegal. It seems that ref return cannot be used if the value to return comes from a nested method with any ref/out arguments.
public static ref T RefReturn<T>()
{
ref T result = ref GetResult<T>(normalParam: default); // compiles
// ref T result = ref GetResult<T>(out bool outParam); // CS8157 at the return statement
// ref T result = ref GetResult<T>(boxedParam: new StrongBox<bool>()); // a suboptimal workaround
// ... code
return ref result;
}
// the bodies below are just dummy examples
private static ref T GetResult<T>(bool normalParam) => ref (new T[1])[0];
// note that this method compiles in itself but unlike in case of the the previous method
// it is illegal to return its result again
private static ref T GetResult<T>(out bool outParam)
{
outParam = true;
return ref (new T[1])[0];
}
// though a ref/out parameter does not work we can mimic something similar without
// making it impossible to return its result from a caller
private static ref T GetResult<T>(StrongBox<bool> boxedParam)
{
boxedParam.Value = true;
return ref (new T[1])[0];
}
I can live with the workaround but I don't understand how an independent by-ref argument makes this solution harmful. AFAIK they must not be dangerous to the inner ref result; otherwise, the inner method itself should trigger some error, too. Or am I wrong? What do I miss?
Here is the live example of the code sample above.
来源:https://stackoverflow.com/questions/65613857/why-cannot-return-a-nested-ref-return-result-if-the-inner-method-has-another-ref