• 你所不知道的ref


    在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 44
    12     }
    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 : ITestClass
    12     {
    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对象接口,也就是添加了ComImportGuid两个Attribute,然后在调用接口中函数的时候居然可以添加ref,如果把ComImport去掉,编译器就立刻给出错误提示。

    本人猜想可能与Com的调用有关系,但是本人才刚接触Com方面的知识,对C#调用Com方面的知识很了解的很少,因此无法给出这种奇葩语法的解释。不知道广大网友有谁对这方面了解比较多的,欢迎在下面留言交流!

  • 相关阅读:
    2020软件工程个人作业06————软件工程实践总结作业
    2020软件工程作业01
    班级博客V2.1版本更新日志
    博客园班级手机版
    班级帮助文档
    问题累计
    2020 软件工程作业06
    2020 软件工程作业04
    2020 软件工程作业03
    2020软件工程02
  • 原文地址:https://www.cnblogs.com/ILoveSleep/p/3821281.html
Copyright © 2020-2023  润新知