获取对数组内部结构的引用 [英] Get a reference to a struct inside array
问题描述
我想修改数组内结构的字段,而不必设置整个结构.在下面的示例中,我想在数组中设置元素 543 的一个字段.我不想复制整个元素(因为复制 MassiveStruct 会影响性能).
I want to modify a field of a struct which is inside an array without having to set entire struct. In the example below, I want to set one field of element 543 in the array. I don't want to have to copy entire element (because copying MassiveStruct would hurt performance).
class P
{
struct S
{
public int a;
public MassiveStruct b;
}
void f(ref S s)
{
s.a = 3;
}
public static void Main()
{
S[] s = new S[1000];
f(ref s[543]); // Error: An object reference is required for the non-static field, method, or property
}
}
有没有办法在 C# 中做到这一点?还是我总是必须从数组中复制整个结构,修改副本,然后将修改后的副本放回数组中.
Is there a way to do it in C#? Or do I always have to copy entire struct out of array, modify the copy, and then put the modified copy back into array.
推荐答案
唯一的问题是您试图从静态方法调用 实例 方法,而没有 的实例P
.
The only problem is that you're trying to call an instance method from a static method, without an instance of P
.
使 f
成为一个静态方法(或创建一个 P
的实例以在其上调用它)就可以了.这都是关于阅读编译器错误:)
Make f
a static method (or create an instance of P
on which to call it) and it'll be fine. It's all about reading the compiler error :)
话虽如此,我强烈建议您:
- 尽可能避免创建大量结构
- 尽可能避免创建可变结构
- 避免使用公共字段
这篇关于获取对数组内部结构的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!