得到一个内部结构数组的引用 [英] Get a reference to a struct inside array

查看:139
本文介绍了得到一个内部结构数组的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要修改一个结构这是一个数组中的一个领域,而无需设置整个结构。在下面的例子中,我要设置数组中元素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.

推荐答案

唯一的问题是,你要调用的实例的从一个静态方法的方法,没有实例<$ C $ C> 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 :)

说了这么多,我会的强烈的建议您:

Having said that, I would strongly advise you to:


  • 避免产生大规模的结构,如果在所有可能的

  • 避免创建的可变的结构,如果在所有可能的

  • 避免公共领域

  • Avoid creating massive structs if at all possible
  • Avoid creating mutable structs if at all possible
  • Avoid public fields

这篇关于得到一个内部结构数组的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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