Interesting “params of ref” feature, any workarounds?

前端 未结 5 1215
轮回少年
轮回少年 2020-11-27 19:38

I wonder if there\'s any way something like this would be possible for value types...

public static class ExtensionMethods {
    public static void SetTo(thi         


        
5条回答
  •  感情败类
    2020-11-27 20:13

    This is not possible. To explain why, first read my essay on why it is that we optimize deallocation of local variables of value type by putting them on the stack:

    https://web.archive.org/web/20100224071314/http://blogs.msdn.com/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx

    Now that you understand that, it should be clear why you cannot store a "ref bool" in an array. If you could, then you could have an array which survives longer than the stack variable being referenced. We have two choices: either allow this, and produce programs which crash and die horribly if you get it wrong -- this is the choice made by the designers of C. Or, disallow it, and have a system which is less flexible but more safe. We chose the latter.

    But let's think about this a little deeper. If what you want is to pass around "thing which allows me to set a variable", we have that. That's just a delegate:

    static void DoStuff(this T thing, params Action[] actions)
    {
        foreach(var action in actions) action(thing);
    }
    ...
    bool b = whatever;
    b.DoStuff(x=>{q = x;}, x=>{r = x;} );
    

    Make sense?

提交回复
热议问题