首页 > 解决方案 > 像c#中的指针一样吗?

问题描述

我是 c# 的新手(一般是和编码),我找不到任何等效的指针。
当我搜索谷歌时,我得到了安全/不安全之类的东西,但这不是我需要的。

就像在 c++ 中一样,如果你有一个指针并且它指向某个值,那么指针的变化会导致原始变量的变化。c#中有这样的东西吗?
例子-

static class universal
{
   public static int a = 10;
}

class class_a
{
   public void change1()
   {
      universal.a--;
   }
}

class class_b
{
   public void change2()
   {
      some_keyword temp = universal.a; //change in temp gives change in a
      temp-= 5; //the purpose of temp is to NOT have to write universal.a each time
   }
}

...

static void Main(string[] args)
{
   class_b B = new class_b();
   class_a A = new class_a();
   A.change1();
   Console.WriteLine(universal.a);//it will print 9

   B.change2();
   Console.WriteLine(universal.a);//it will print 4
   Console.ReadKey();
}

编辑-谢谢@Sweeper,我得到了答案,我必须使用 ref int temp = ref universal.a;

标签: c#c++classpointerscall-by-value

解决方案


C#references与指针非常相似。如果ab都是对同一个对象的引用,那么在 中a也会出现变化b

例如,在:

class X {
    public int val;
}

void Main()
{
    var a = new X();
    var b = a;
    a.val = 6;
    Console.WriteLine(b.val);
}

6将被写入。

如果您将Xfrom的声明更改classstruct,则aandb将不再是引用,并且0将被写入。


推荐阅读