保存到一个int类型的引用 [英] Saving a reference to a int
问题描述
下面是我所试图做的。
static void Main(string[] args)
{
int test = 0;
int test2 = 0;
Test A = new Test(ref test);
Test B = new Test(ref test);
Test C = new Test(ref test2);
A.write(); //Writes 1 should write 1
B.write(); //Writes 1 should write 2
C.write(); //Writes 1 should write 1
Console.ReadLine();
}
class Test
{
int _a;
public Test(ref int a)
{
_a = a; //I loose the reference here
}
public void write()
{
var b = System.Threading.Interlocked.Increment(ref _a);
Console.WriteLine(b);
}
}
在我真正的代码中,我有一个int值会由多个线程但是当线程称它不会是容易通过它指向它在INT(在这里面发生的真正的代码参数递增的IEnumerator
)。因此,一个要求是引用必须在构造函数中进行。也并非所有的线程将在同一单碱基INT被人指指点点,所以我也不能使用全局静态int值。我知道我可以只框类内部INT和周围传递类,但我想知道这是做这样的事情的正确方法是什么?
In my real code I have a int that will be incremented by many threads however where the threads a called it will not be easy to pass it the parameter that points it at the int(In the real code this is happening inside a IEnumerator
). So a requirement is the reference must be made in the constructor. Also not all threads will be pointing at the same single base int so I can not use a global static int either. I know I can just box the int inside a class and pass the class around but I wanted to know if that is the correct way of doing something like this?
我认为可能是正确的方法:
What I think could be the correct way:
static void Main(string[] args)
{
Holder holder = new Holder(0);
Holder holder2 = new Holder(0);
Test A = new Test(holder);
Test B = new Test(holder);
Test C = new Test(holder2);
A.write(); //Writes 1 should write 1
B.write(); //Writes 2 should write 2
C.write(); //Writes 1 should write 1
Console.ReadLine();
}
class Holder
{
public Holder(int i)
{
num = i;
}
public int num;
}
class Test
{
Holder _holder;
public Test(Holder holder)
{
_holder = holder;
}
public void write()
{
var b = System.Threading.Interlocked.Increment(ref _holder.num);
Console.WriteLine(b);
}
}
难道还有比这更好的办法吗?
Is there a better way than this?
推荐答案
基本上,答案是肯定的,你需要一个类。
Basically, the answer is Yes, you need a class.
有是没有的参考诠释',你可以存储为一个领域的概念。在C#中也仅限于参数。
There is no concept of 'reference to int' that you can store as a field. In C# it is limited to parameters.
虽然有一个不安全
办法(指针为int,为int *
)的处理在该方案中的GC的复杂性使它不切实际和效率低下。
And while there is an unsafe
way (pointer to int, int*
) the complexities of dealing with the GC in that scenario make it impractical and inefficient.
所以,你的第二个例子看起来不错。
So your second example looks OK.
这篇关于保存到一个int类型的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!