In C #, there is a keyword called ref, which is used to transmit parameters by reference. The basic usage is as follows:
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 }
It can be seen that when the keyword ref is used, when the function declaration can be called, The ref must be added to the parameter; otherwise, the compiler will prompt an error:
But is that true?
See the following code.
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 }
Did you find anything special? By the way, there are 20th rows of function calls. You are not mistaken. when calling the function, you did not add a ref, but the code was compiled (I tested it in vs2010). Isn't that amazing.
The focus of this Code is to declare the interface as a COM object interface, that is, to add the comimport and guid attributes, and then add the ref when calling the functions in the interface, if you remove comimport, the compiler immediately returns an error message.
I guess it may be related to the call of COM, but I have just been familiar with COM and have little knowledge about C # Calling com. Therefore, I cannot explain this wonderful syntax. I don't know who knows much about this. Please leave a message below!