/// <summary>
/// 第十六章:处理二进制数据和使用索引器
/// </summary>
namespace Chapter16
{
class Program
{
static void Main(string[] args)
{
//16.1什么是索引器
/*索引器可被视为一种智能数组*/
///16.1.1存储二进制值
uint binData = 0b01111;//二进制
uint hexDate = 0x0_0F;//十六进制
///16.1.2显示二进制值
Console.WriteLine($"{Convert.ToString(binData, 2)}");//其中2是进制数
///16.1.3操作二进制数
/*
* NOT操作符:~(1变0,0变1)
* 左移位操作符:<<(向左移两个位置,补0)
* OR操作符:|(有1则1)
* AND操作符:&(全为1才是1)
* XOR操作符:^(不同数字,则为1)
*/
///16.1.4用索引器解决相同问题
/*
* 注意:
* 1.索引器不是方法——没有一对包含参数的圆括号,但有一对指定了索引的方括号。索引指定要访问哪一个元素。
* 2.所有索引器都使用this关键字取代方法名。每个类或结构只允许定义一个索引器,而且总是命名为this。
* 3.和属性一样,索引器也包含get和set这两个访问器。
* 4.索引器声明中指定的index将用调用索引器时指定的索引值来填充。get和set访问器方法可以读取该实参,判断应该访问哪一个元素。
*/
int adapted = 0b0_01111110;
IntBits bits = new IntBits(adapted);
bool peek = bits[6];
bits[0] = true;
bits[3] = false;
Console.WriteLine($"{bits}");
//16.2理解索引器的访问器
bits[6] ^= true;//反转bits变量索引6的二进制位
//16.3对比索引器的数组
/*
*区别:
* 1.索引器能使用非数值下标,而数组只能使用整数下标
* 2.索引器能重载(和方法相似),而数组不能;
* 3.索引器不能作为ref或out参数使用,数组元素则能。
*/
//16.4接口中的索引器
//16.5在windows应用程序中使用索引器
Console.ReadLine();
}
/// <summary>
/// 16.1.4用索引器解决相同问题
/// </summary>
struct IntBits
{
private int bits;
public IntBits(int init) => bits = init;
public bool this [int index]
{
get => (bits & (1 << index)) != 0;
set
{
if (value)
bits |= (1 << index);
else
bits &= ~(1 << index);
}
}
public override string ToString()
{
return Convert.ToString(bits, 2);
}
}
/// <summary>
/// 16.4接口中的索引器
/// </summary>
interface IRawInt
{
bool this[int index] { get;set; }
}
struct RawInt : IRawInt
{
public bool this[int index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
}
}
}
//第17章:泛型概念
namespace Chapter17
{
class Program<T>
{
private T[] data;
static void Main(string[] args)
{
//17.1object的问题(显示类型转换导致灵活性降低)
//17.2泛型解决方案(泛型避免强制类型转换)
///17.2.1对比泛型类和常规类
/*
* 常规类能强制转换为不同的类型
* 泛型类的具体类型版本称为已构造类型
*/
///17.2.2泛型和约束
/*
*为了确保泛型类使用的类型参数是提供了特定方法的类型就要用到约束
* 约束限制泛型类的类型参数实现了一组特定接口,因而提供了接口定义的方法
*/
//17.3创建泛型类
///17.3.1二叉树理论
///17.3.2使用泛型构造二叉树类
//17.4创建泛型方法
int a = 1, b = 2;
Swap<int>(ref a, ref b);
//17.5可变性和泛型接口
///17.5.1协变接口
///17.5.2逆变接口
}
public T Dequeue()//t作为返回址的类型
{
T queueItem = this.data[0];//数组中的数据是‘T’类型
return queueItem;
}
static void Swap<T>(ref T first,ref T second)
{
T temp = first;
first = second;
second = temp;
}
}
}