7.1 分部类型

7.1.1 在多个文件中创建一个类型

 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             Console.ReadKey();
 6         }
 7     }
 8     partial class Example<TFirst, TSecond> : IEquatable<string> where TFirst : class
 9     {
10         
11     }
12     partial class Example<TFirst, TSecond> : EventArgs, IDisposable
13     {
14         public void Dispose()
15         {
16             throw new NotImplementedException();
17         }
18         public bool Equals(string other)
19         {
20             return false;
21         }
22     }

 7.1.3 C# 3 独有的分部方法

 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             PartialMethodDemo demo = new PartialMethodDemo();
 6 
 7             Console.ReadKey();
 8         }
 9     }
10     partial class PartialMethodDemo
11     {
12         public PartialMethodDemo()
13         {
14             OnConstructorStart();
15             Console.WriteLine("generate constructor");
16             OnConstructorEnd();
17         }
18         partial void OnConstructorStart();
19         partial void OnConstructorEnd();
20     }
21     partial class PartialMethodDemo
22     {
23         partial void OnConstructorStart()
24         {
25             
26         }
27         partial void OnConstructorEnd()
28         {
29             Console.WriteLine("manual code");
30         }
31     }

  对 PartialMethodDemo 的无参构造函数进行调用,输出结果为“Generated constructor”,接着“Manual code”也会被打印出来。
分析构造函数的IL,你不会看到对 OnConstructorStart的调用,因为它已经不存在了——在这个编译好的类型中,没有它的任何痕迹。
由于方法可能不存在,分部方法返回类型必须为 void ,且不能获取 out 参数。它们必须是私有的,但可以是静态的或泛型的。
如果方法没有在任何文件中实现,那么整个调用语句就会被移除,包括任何参数计算。
如果任何你打算进行的参数计算具有副作用,那么你应该单独执行这些计算,不管分部方法是否实现

猜你喜欢

转载自www.cnblogs.com/kikyoqiang/p/10029495.html
7.1