C#基础-第10章:属性
10.1 本章内容:
- 无参属性
- 有参属性
- 调用属性访问方法时的性能
- 属性访问器的可访问性
- 泛型属性访问器的方法
/* ============================================================================== ============================================================================== */ using System; using System.IO; using System.Linq; using System.Collections.Generic; public static class Program { public static void Main() { ParameterlessProperties.Go(); AnonymousTypesAndTuples.Go(); BitArrayTest(); } private static void BitArrayTest()//P215 索引器调用 { // 分配行14个位的bitarray数组 BitArray ba = new BitArray(14); // 调用set访问器方法,将编号为偶数的所有位都设为true for (Int32 x = 0; x < 14; x++) { ba[x] = (x % 2 == 0); } // 调用get访问器方法显示所有位的状态 for (Int32 x = 0; x < 14; x++) { Console.WriteLine("Bit " + x + " is " + (ba[x] ? "On" : "Off")); } } } internal static class ParameterlessProperties { public static void Go() { Employee emp = new Employee(); emp.Name = "Jeffrey Richter"; emp.Age = 45; //设置年龄 Console.WriteLine("Employee info: Name = {0}, Age = {1}", emp.Name, emp.Age); try { emp.Age = -5; //抛出异常 } catch (ArgumentOutOfRangeException e) { Console.WriteLine(e); } Console.WriteLine("Employee info: Name = {0}, Age = {1}", emp.Name, emp.Age); } private sealed class Employee { private String m_Name; // 字段现在是私有的 private Int32 m_Age; // 字段现在是私有的 public String Name { get { return (m_Name); } set { m_Name = value; } // 关键字values总是代表新值 } public Int32 Age { get { return (m_Age); } set { if (value <= 0) // // 关键字values总是代表新值 throw new ArgumentOutOfRangeException("value", "must be >0"); m_Age = value; } } } } internal static class AnonymousTypesAndTuples { public static void Go() { AnonymousTypes(); TupleTypes(); Expando(); } private static void AnonymousTypes()//P209 { // 定义类型,构造实例,并初始化属性 var o1 = new { Name = "Jeff", Year = 1964 }; // 在控制台上显示属性:Name=Jeff,Year=1964 Console.WriteLine("Name={0}, Year={1}", o1.Name, o1.Year); String Name = "Grant"; DateTime dt = DateTime.Now; var o2 = new { Name, dt.Year }; ShowVariableType(o1); ShowVariableType(o2); Console.WriteLine("Types are same: " + (o1.GetType() == o2.GetType())); // 一个类型允许相等测试和赋值操作 Console.WriteLine("Objects are equal: " + o1.Equals(o2)); o1 = o2; // 赋值 var people = new[] { o1, new { Name = "Kristin", Year = 1970 }, new { Name = "Aidan", Year = 2003 }, new { Name = "Grant", Year = 2008 } }; foreach (var person in people) Console.WriteLine("Person={0}, Year={1}", person.Name, person.Year); String myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var query = from pathname in Directory.GetFiles(myDocuments) let LastWriteTime = File.GetLastWriteTime(pathname) where LastWriteTime > (DateTime.Now - TimeSpan.FromDays(7)) orderby LastWriteTime select new { Path = pathname, LastWriteTime }; foreach (var file in query) Console.WriteLine("LastWriteTime={0}, Path={1}", file.LastWriteTime, file.Path); } private static void ShowVariableType<T>(T t) { Console.WriteLine(typeof(T)); } /************ System.Tupele 类型 **********************/ //用Item1返回最小值&用Item2返回最大值 private static Tuple<Int32, Int32> MinMax(Int32 a, Int32 b) { return Tuple.Create(Math.Min(a, b), Math.Max(a, b)); //return new Tuple<Int32, Int32>(Math.Min(a, b), Math.Max(a, b)); } // 下面展示了如何调用方法,以及如何使用返回的Tuple private static void TupleTypes()//P213 { var minmax = MinMax(6, 2); Console.WriteLine("Min={0}, Max={1}", minmax.Item1, minmax.Item2); var t = Tuple.Create(0, 1, 2, 3, 4, 5, 6, Tuple.Create(7, 8)); Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}", t.Item1, t.Item2, t.Item3, t.Item4, t.Item5, t.Item6, t.Item7, t.Rest.Item1.Item1, t.Rest.Item1.Item2); } private static void Expando()//P214 { dynamic e = new System.Dynamic.ExpandoObject(); e.x = 6; // 添加一个Int32 ‘x’属性,其值为6 e.y = "Jeff"; // 添加一个String ‘y’属性,其值为Jeff e.z = null; // 添加一个object‘z’属性,其值为null // 查看所有属性及其值: foreach (var v in (IDictionary<String, Object>)e) Console.WriteLine("Key={0}, V={1}", v.Key, v.Value); // 删除x属性及其值; ((IDictionary<String, Object>)e).Remove("x"); } } internal sealed class BitArray//P(214) { //容纳了二进制为的私有字节数组 private Byte[] m_byteArray; private Int32 m_numBits; // 下面构造器用于分配字节数组,并将所有位设为0 public BitArray(Int32 numBits) { // 先验证实参 if (numBits <= 0) throw new ArgumentOutOfRangeException("numBits must be > 0"); // 保存位的个数 m_numBits = numBits; //为位数组分配字节 m_byteArray = new Byte[(m_numBits + 7) / 8]; } // 下面是索引器(有参属性) public Boolean this[Int32 bitPos] { // 下面是索引器的get访问器方法 get { // 先验证实参 if ((bitPos < 0) || (bitPos >= m_numBits)) throw new ArgumentOutOfRangeException("bitPos", "bitPos must be between 0 and " + m_numBits); // 返回指定索引处的位的状态 return ((m_byteArray[bitPos / 8] & (1 << (bitPos % 8))) != 0); } // 下面是索引器的set访问器方法 set { if ((bitPos < 0) || (bitPos >= m_numBits)) throw new ArgumentOutOfRangeException("bitPos", "bitPos must be between 0 and " + m_numBits); if (value) { // 将指定索引处的位设为ture m_byteArray[bitPos / 8] = (Byte) (m_byteArray[bitPos / 8] | (1 << (bitPos % 8))); } else { //将指定索引处的位设为false m_byteArray[bitPos / 8] = (Byte) (m_byteArray[bitPos / 8] & ~(1 << (bitPos % 8))); } } } }