标签:
#region 7-1演示分部类型的混合声明 partial class Example<TFirst, TSecond> : IEquatable<string> where TFirst : class//接口和类型的参数约束,如果实现基类,则必须为EventArgs { public bool Equals(string other)//实现IEquatable<string> { return false; } } partial class Example<TFirst, TSecond> : EventArgs, IDisposable//指定基类和接口,不能进行参数约束 { public void Dispose()//实现IDisposable { } } #endregion#region 7-2分部方法在构造函数中被调用 partial class PartialMethodDemo { public PartialMethodDemo() { OnConstructorStart(); Console.WriteLine("Generated constructor"); OnConstructorEnd(); } partial void OnConstructorStart();//方法没有实现,将被移除,IL中不存在 partial void OnConstructorEnd();//分部方法和抽象方法相同:只使用partial修饰符提供签名无需实现 } partial class PartialMethodDemo { partial void OnConstructorEnd()//实际实现需要partial,返回类型必须是void,不能获取out参数,它们是私有的 { Console.WriteLine("Manual code"); } } #endregion #region 7-3典型的C#1工具类 public sealed class NonStaticStringHelper//密封类防止派生 { private NonStaticStringHelper()//提供一个私有的构造函数,防止其他代码对其进行实例化 { } public static string Reverse(string input)//所有方法都是静态的 { char[] chars = input.ToCharArray(); Array.Reverse(chars); return new string(chars); } } #endregion #region 7-4将代码7-3中的工具类转化为一个C#2的静态类 public static class StringHelper { public static string Reverse(string input) { char[] chars = input.ToCharArray(); Array.Reverse(chars); return new string(chars); } } #endregionusing WinForms = System.Windows.Forms; namespace 第七章结束Csheep2的讲解最后一些特性窗体{ class WinForms { };//名字同为WinForms public partial class Form1 : Form { public Form1() { InitializeComponent(); Type s2 = typeof(WinForms::Button);//使用::告知编译器WinForms仍然做别名使用 } }}class Configuration { }namespace 第七章结束Csheep2的讲解最后一些特性{ class Program { class Configuration { } static void Main(string[] args) { #region 7-7使用全局命名空间别名来准确的设定想要的类型 Console.WriteLine(typeof(Configuration));//打印:第七章结束Csheep2的讲解最后一些特性.Program+Configuration 移动命名空间之前就把Configuration解析为这个类型 Console.WriteLine(typeof(global::Configuration));//打印:Configuration Console.WriteLine(typeof(global::第七章结束Csheep2的讲解最后一些特性.Program)); #endregion Console.ReadKey(); } } #region 7-9包含了未用字段的类 public class FieldUsedOnlyByflection { #region 7-10禁用和恢复警告 #pragma warning disable 0169 //禁用警告 int x;#pragma warning restore 0169//恢复警告 #endregion } #endregion[assembly: InternalsVisibleTo("FriendAssembly")]//只能用于程序集,授予FriendAssembly额外的访问权限namespace Source{ #region 7-12友元程序集的演示 public class Source1 { internal static void InternalMethod()//在FriendAssembly可被访问 { Console.WriteLine("InternalMethod()"); } public static void PublicMethod() { Console.WriteLine("PublicMethod()"); } } #endregion}namespace FriendAssembly{ public class Class1 { public void test() { Source1.PublicMethod(); Source1.InternalMethod(); } }}标签:
原文地址:http://www.cnblogs.com/Tan-sir/p/5169212.html