为什么会使用"in"? C#中的参数修饰符? [英] Why would one ever use the "in" parameter modifier in C#?

查看:181
本文介绍了为什么会使用"in"? C#中的参数修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我(我想)了解了 in 参数修饰符的作用.但是它的确显得很多余.

So, I (think I) understand what the in parameter modifier does. But what it does appears to be quite redundant.

通常,我认为使用 ref 的唯一原因是修改调用变量,而 in 明确禁止了该变量.因此,通过 in 引用传递在逻辑上似乎等效于按值传递.

Usually, I'd think that the only reason to use a ref would be to modify the calling variable, which is explicitly forbidden by in. So passing by in reference seems logically equivalent to passing by value.

是否有某种性能优势?我认为,在后端, ref 参数必须至少复制变量的物理地址,该地址的大小应与任何典型对象引用的大小相同.

Is there some sort of performance advantage? It was my belief that on the back-end side of things, a ref parameter must at least copy the physical address of the variable, which should be the same size as any typical object reference.

那么,优点是仅在较大的结构中出现,还是在幕后进行了一些编译器优化,使其在其他地方有吸引力?如果是后者,为什么我不应该将每个参数都设置为 in ?

So, then is the advantage just in larger structs, or is there some behind-the-scenes compiler optimization that makes it attractive elsewhere? If the latter, why shouldn't I make every parameter an in?

推荐答案

in最近被引入C#语言.

in was recently introduced to the C# language.

in实际上是ref readonly.一般而言,只有in有用的一种用例:处理大量大型readonly struct的高性能应用.

in is actually a ref readonly. Generally speaking, there is only one use case where in can be helpful: high performance apps dealing with lots of large readonly structs.

假设您拥有:

readonly struct VeryLarge
{
    public readonly long Value1;   
    public readonly long Value2;

    public long Compute() { }
    // etc
}

void Process(in VeryLarge value) { }

在这种情况下,当在Process方法中使用此结构时(例如,调用value.Compute()时),将按引用传递VeryLarge结构而不创建防御性副本,并且通过编译器.

In that case, the VeryLarge struct will be passed by-reference without creating of defensive copies when using this struct in the Process method (e.g. when calling value.Compute()), and the struct immutability is ensured by the compiler.

请注意,在调用struct的方法并访问上述Process方法中的属性时,传递带有in修饰符的非只读struct会导致编译器创建防御性副本,这会对性能产生负面影响!

Note that passing a not-readonly struct with an in modifier will cause the compiler to create a defensive copy when calling struct's methods and accessing properties in the Process method above, which will negatively affect performance!

有一个非常好的

There is a really good MSDN blog entry which I recommend to carefully read.

如果您想了解in的更多历史背景,可以阅读在C#语言的GitHub存储库中进行讨论.

If you would like to get some more historical background of in-introducing, you could read this discussion in the C# language's GitHub repository.

通常,大多数开发人员都同意将in引入是错误的.这是一种相当奇特的语言功能,仅在高性能的情况下才有用.

In general, most developers agree that introducing of in could be seen as a mistake. It's a rather exotic language feature and can only be useful in high-perf edge cases.

这篇关于为什么会使用"in"? C#中的参数修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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