有趣的“参考参数"功能,任何解决方法? [英] Interesting "params of ref" feature, any workarounds?

查看:25
本文介绍了有趣的“参考参数"功能,任何解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道对于值类型是否有任何可能的方式......

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

public static class ExtensionMethods {
    public static void SetTo(this Boolean source, params Boolean[] bools) {
        for (int i = 0; i < bools.Length; i++) {
            bools[i] = source;
        }
    }
}

那么这将是可能的:

Boolean a = true, b, c = true, d = true, e;
b.SetTo(a, c, d, e);

当然,这行不通,因为 bool 是值类型,所以它们作为值传递给函数,而不是作为引用.

Of course, this does not work because the bools are a value type so they are passed into the function as a value, not as a reference.

除了将值类型包装成引用类型(通过创建另一个类)之外,还有什么方法可以在使用 params 修饰符的同时通过引用 (ref) 将变量传递给函数?

Other than wrapping the value types into reference types (by creating another class), is there any way to pass a variable into function by the reference (ref) while using params modifier?

推荐答案

这是不可能的.为了解释原因,首先阅读我的文章,为什么我们通过将值类型的局部变量放在堆栈上来优化它们的释放:

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

既然您明白了这一点,就应该清楚为什么不能在数组中存储ref bool"了.如果可以,那么您可以拥有一个比被引用的堆栈变量存活时间更长的数组.我们有两个选择:要么允许它,如果你弄错了,程序会崩溃并死掉——这是 C 的设计者做出的选择. 或者,不允许它,并拥有一个不太灵活但更多安全的.我们选择了后者.

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<T>(this T thing, params Action<T>[] actions)
{
    foreach(var action in actions) action(thing);
}
...
bool b = whatever;
b.DoStuff(x=>{q = x;}, x=>{r = x;} );

有意义吗?

这篇关于有趣的“参考参数"功能,任何解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆