开发者

Is there some trick to use 'out' parameters inside lambda function? [duplicate]

This question already has answers here: Func<T> with out parameter (4 answers) Closed 9 years ago.
if ( (new Func</*out*/ string, bool>( (/*out*/ string uname) => ....

more details : that is a part of login function and I just want that my lambda function to changes login-name user with a out parameter and said me that user logined with it's bool return.

I really understand that I can return the Tuple and then get my string value but I want exactly out parameter for开发者_StackOverflow社区 some personal clarity. I better return only string with null if user is not login, just want to know if I can use out parameters inside lambda functions.

And I really get that the code with expressions on the statement places is not so clean But none said me if that is really bad for compiler.


Lambda expressions won't work, but for delegates you should be fine using a statement body:

bool outval = false; // definite assignment
Func<bool> func = () => {
    return SomeMethod(out foo);
};
bool returned = func();
// check both outval and returned

For delegates... You will need to define your own:

public delegate bool MyType(out string value);


While you can't use the out keyword I did find a solution that lets you basically achieve C++ style memory pointers in .NET. I found this class due to the very reason you opened this SO question not being able to use an out parameter where I wanted it.

public class Ptr<T>
{
    Func<T> getter;
    Action<T> setter;

    public Ptr(Func<T> g, Action<T> s)
    {
        getter = g;
        setter = s;
    }

    public T Deref
    {
        get { return getter(); }
        set { setter(value); }
    }
}

Usage example

private IDocumentSession _session = DocumentStore.OpenSession()

var ptr = new Ptr<IDocumentSession>(
                () => _session, 
                newValue => _session = newValue))

session.Deref.SaveChanges();
session.Deref = DocumentStore.OpenSession();

I use this in a batch program that allows batch operations to control session flushing with RavenDB when I need fine grained session control while also leaving an ambient session context. Word of warning I have no idea what implications this type of code would have in a long running production app since I'm not sure if this would confuse the GC and cause memory to never be reclaimed.


You cannot use out parameters with a lambda expression. See this Stack Overflow question.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜