標籤:style blog http color 使用 strong
在c#中有個關鍵字叫ref,它的作用是使參數按引用傳遞,基本用法如下:
1 class RefExample 2 { 3 static void Method(ref int i) 4 { 5 i = 44; 6 } 7 static void Main() 8 { 9 int val = 0;10 Method(ref val);11 // val is now 4412 }13 }
可見,關鍵字ref在使用的時候,在函式宣告可函數調用的時候,在參數上必須添加ref,否則編譯器就會提示錯誤:
但真的是這樣的嗎?
請看如下的代碼
1 public class Class1 2 { 3 public int Int { get; set; } 4 public DateTime Time { get; set; } 5 } 6 [ComImport, Guid("B2E23B44-FD50-4131-94C7-7D9569837289")] 7 interface ITestClass 8 { 9 void TestFunc(ref int i, ref DateTime t);10 }11 class TestClass : ITestClass12 {13 public void TestFunc(ref int i, ref DateTime t)14 {15 }16 public static void Main()17 {18 ITestClass test = new TestClass();19 var obj = new Class1();20 test.TestFunc(obj.Int, obj.Time);21 }22 }
發現有什麼特別的嗎?對了,就是第20行的函數調用,你沒有看錯,調用函數的時候確實沒有添加ref,但是編譯通過(本人在vs2010中測試通過),是不是很奇葩呢。
這段代碼的重點就在於將介面聲明稱一個Com對象介面,也就是添加了ComImport和Guid兩個Attribute,然後在調用介面中函數的時候居然可以添加ref,如果把ComImport去掉,編譯器就立刻給出錯誤提示。
本人猜想可能與Com的調用有關係,但是本人才剛接觸Com方面的知識,對C#調用Com方面的知識很瞭解的很少,因此無法給出這種奇葩文法的解釋。不知道廣大網友有誰對這方面瞭解比較多的,歡迎在下面留言交流!