1

让我解释一下我的情况。我有一个程序读取外部连接并给我一个整数(或布尔值)数组。这些输入应该提供一个具有某些属性(例如 X、Y、Z)的对象。因此,如果读取数组上的值,我应该将这些值写入属性中。有没有办法通过 ref 传递这些值(例如)?从逻辑上思考,最好的方法是指针(指向数组 [0] 的属性 X),但这些对我来说并不是很清楚。

我可以创建一种方法来查找数组中的更改(但它是一个非常大的数组,+60000),然后更新我的对象。但我认为这将是一个坏主意。

对不起,如果我写了任何废话,我只是从 C# 开始。

一些伪代码来帮助。

class obj
{
      int X {get; set;}
      public obj(ref int x)
      {
          X = x;
      }
}

class main 
{
      void main()
      {
         int a;

         obj test = new obj(ref a);
      }
}

所以如果:a = 10,obj.X = 10 也是。

4

1 回答 1

0
public class MyClass
{
    private int[] backingArray;
    public int X
    {
        get
        {
            if (backingArray == null)
                return -1;
            else
                return backingArray[0];
        }
    }
    public MyClass(int[] array)
    {
        if (array.Length > 0)
            backingArray = array;
    }
}

class Main
{
    void Main()
    {
        int[] array = new int[] { 2 };

        MyClass test = new MyClass(array);
        array[0] = 6;
        Console.WriteLine(test.X);//prints 6
    }
}

Of course this only works with reference types (arrays are reference types). If you wanted to do this whole thing with a value type, you'd need to "wrap" it in some reference type. You can use a class such as the following to wrap anything if you don't have anything convenient.

public class Wrapper<T>
{
    public T Value { get; set; }
}

It's not possible to use ref in the manor that you've shown in the OP. You wouldn't be able to store the value that was passed by reference. If you could, then you could end up passing some value on the stack and then having the created object that holds the reference living longer than the item on the stack. If that happened you would end up with a reference it a location in memory that no longer holds the variable you intended. This was somewhat of a gotcha in C++ that the designers of C# went out of their way to ensure can't happen (at least not without a lot of work).

于 2012-08-29T17:30:22.487 回答