你所不知道的ref

來源:互聯網
上載者:User

標籤: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方面的知識很瞭解的很少,因此無法給出這種奇葩文法的解釋。不知道廣大網友有誰對這方面瞭解比較多的,歡迎在下面留言交流!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.