有趣的“参考参数"功能,任何解决方法?

编程入门 行业动态 更新时间:2024-10-26 01:30:30
本文介绍了有趣的“参考参数"功能,任何解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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:

web.archive/web/20100224071314/blogs.msdn/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;} );

有意义吗?

更多推荐

有趣的“参考参数"功能,任何解决方法?

本文发布于:2023-05-28 12:27:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/320891.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file &#039;D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!