有趣的"参考&QUOT的PARAMS;功能,任何变通办法? [英] Interesting "params of ref" feature, any workarounds?

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

问题描述

我不知道是否有这样的事情任何方式将是可能的值类型...

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;
		}
	}
}

那么这将是可能的:

then this would be possible:

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

当然,这并不工作,因为是布尔变量的值类型,因此它们被传递到函数作为一个值,而不是作为一个参考。

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.

除了包装的价值类型为引用类型(通过创建另一个类),有没有办法通过引用(REF)给一个变量传递到功能,而使用params修饰符?

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:

<一个href=\"http://blogs.msdn.com/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx\">http://blogs.msdn.com/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx

现在,你明白,应该很清楚为什么你不能存放在数组中的参考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;} );

请有意义吗?

这篇关于有趣的&QUOT;参考&QUOT的PARAMS;功能,任何变通办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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