2017-04-06 93 views
1

在C++中可以通過引用(&)或指針(*)來完成。在C#中有「ref」。如何從表格中獲取價值並通過參考來改變它?從表中獲取值作爲參考

namespace Rextester 
{ 
    public class Program 
    { 
     public static void Main(string[] args) 
     { 
      int[] t=new int[3]{1,2,3}; 
      int a=t[0]; //ref int a=t[0]; 
      a+=10; 
      System.Console.WriteLine("a={0}", a); //11 
      System.Console.WriteLine("t[0]={0}", t[0]); //1 
     } 
    } 
} 

例如,在C + +

int &a=tab[0]; 
+0

這裏很重要的一點是,* C#不是C++ *。沒有規則說這只是因爲它存在於C++中,因此它必須存在於C#中。 – Default

回答

6

這僅成爲在C#7是可行的,採用REF當地人

public class Program 
{ 
    public static void Main(string[] args) 
    { 
     int[] t = {1, 2, 3}; 
     ref int a = ref t[0]; 
     a += 10; 
     System.Console.WriteLine($"a={a}");  // 11 
     System.Console.WriteLine($"t[0]={t[0]}"); // 11 
    } 
} 

這是重要的線:

ref int a = ref t[0]; 

C#7也支持REF返回。我會建議儘量使用這兩個功能 - 雖然它們當然可以有用,但許多C#開發人員都不熟悉它們,而且我可以看到它們造成重大混淆。

-1

不是。對於像int這樣的值類型是不可能的。但是,它是參考類型的標準。

例如:

class MyClass 
{ 
    public int MyProperty {get; set;} 
} 

void Main() 
{ 
    var t=new MyClass[3]{new MyClass {MyProperty=1},new MyClass {MyProperty=2},new MyClass {MyProperty=3}}; 
    var a=t[0]; //ref int a=t[0]; 
    a.MyProperty+= 10; 
    System.Console.WriteLine("a={0}", a.MyProperty); //11 
    System.Console.WriteLine("t[0]={0}", t[0].MyProperty); //11 
} 

給出了預期的結果。

編輯:顯然我在後面。正如Jon Skeet指出的那樣,在C#7.0中是可能的。

1

它可以與指針在不安全模式

unsafe 
{ 
     int[] t = new int[3] { 1, 2, 3 }; 
     fixed (int* lastPointOfArray = &t[2]) 
     { 
      *lastPointOfArray = 6; 
      Console.WriteLine("last item of array {0}", t[2]); // =>> last item of array 6 
     } 
}