在C ++中,我可以做这样的事情:
In C++, I can do something like this:
int i[10] = new int[10]; int *p = &i[5];然后,我可以随时知道p指向int数组我的第5个元素,无论我的内容。
Then, I can always know that p points to the 5th element of int array i, regardless of i's contents.
有没有办法做到在C#中类似的东西?
Is there any way to do something similar in C#?
我意识到这是可能的,其中C#保护我们从我们自己的一种方式,所以我不是在寻找一个确切的equivelent,而是一个类似的概念...也就是说,能够指一些其他变量的内容,而不是变量本身的实例
I realize this is likely one of the ways in which C# "protects" us from ourselves, so i'm not looking for an exact equivelent, but rather a similar concept... that is, being able to refer to the contents of some other variable, rather than the instance of the variable itself.
下面是我使用的情况下我在想。我有一个字符串数组。我想有这些数组元素引用另一个数组。事情是这样的(显然不是有效的code):
Here's my use case i'm thinking of. I have an array of strings. I would like to have another array of references to those array elements. Something like this (obviously not valid code):
string[] s = new string[] { "one", "two", "three", "four", "five", "six" }; stringref[] sr = new stringref[] { &s[0], &s[1], &s[2], &s[3], &s[4], &s[5] }; Console.WriteLine(sr[1]); // == "two" s[1] = "two point zero"; Console.WriteLine(sr[1]); // == "two point zero"当然,裁判paramets做到这一点,out参数让你写一个特定的变量。但对于非参数?你可以存储一个参考?你可以保持裁判的数组或字典?
Certainly, ref paramets do this, and out parameters allow you to write to a specific variable. But what about non-parameters? Can you store a ref? Can you keep an array of refs or a dictionary?
这似乎是如果与参数做到这一点的能力,是present,应该有办法做到这一点没有他们。
It seems like if the ability to do it with parameters is present, there should be a way to do it without them.
推荐答案没有。把不安全 code不谈,这确实让持有指向的内存位置,有没有办法给一个变量的引用存放在C#。
No. Putting unsafe code aside, which does allow holding pointers to memory locations, there's no way to store a reference to a variable in C#.
REF 和退出参数提供给需要参考的唯一手段,但你不能将它们保存在任何地方。
ref and out arguments provide the only means to take a reference but you can't save them anywhere.
您可以通过包装领域在类解除此限制,并使用其引用来代替。这是编译器捕捉封变量是什么:
You can workaround this limitation by wrapping fields in a class and using its reference instead. This is what the compiler does to capture variables in closures:
例如,当你写的:
int integer = 0; Action<int> method = i => Console.WriteLine(i + integer); integer = 42; method(100); // prints 142, not 100在第二行中,编译器将不得不采取了匿名方法,并将其存储在类一个单独的方法。显然,这种方法将无法获得整数变量。它在某种程度上需要一个参考,以整数变量传递给该匿名方法。由于它是不可能的,它会生成一个类与现场举行一个整数,并使用了类的实例来存储变量。基本上,本地变量被提升到一个场中的一类,并存储在堆
In the second line, the compiler will have to take out the anonymous method and store it as a separate method in the class. Obviously, that method won't have access to integer variable. It somehow needs to pass a "reference" to integer variable to that anonymous method. Since it's not possible, it'll generate a class with a field to hold an integer and uses an instance of that class to store the variable. Basically, the local variable is promoted to a field in a class and is stored in the heap.
更多推荐
参考在C#中的变量?
发布评论