@sharif
2018-02-26T12:00:12.000000Z
字数 2832
阅读 1028
Ch11
Ch11.2
is
as
比较
目录
GetType()和typeof()一起使用就可以确定对象的类型
boxing是把值类型转换为System.Object类型,或者转换为由值类型实现的接口类型。unboxing是相反的过程。
//假定MyStruct类型实现IMInteface接口
interface IMyInterface{}
struct MyStruct : IMyInterface
{
public int val;
}
//把结构封箱到IMyinterface类型中
Mystruct valType1 = new Mystruct();
IMyInterface refType = valType1;
//拆箱
MyStruct valType2 = (MyStruct)refType;
封箱是在没有用户干涉的情况下进行的(不需要任何代码),但拆箱一个值需要进行显式转换
is运算符并不是用来说明对象是某种类型,而是用来检查是不是给定类型,或者是否可以转换为给定类型,如果是,返回 true。
is和==的区别在于,前一个是属于,后一个是等于。
<operand> is <type>
类型 | return true |
---|---|
类类型 | 相同类类型 或者继承该类型或者封箱到该类型中 |
接口类型 | 相同类类型 或者实现了该接口的类型 |
值类型 | 相同类类型 或者可以拆箱到该类型中 |
public class AddClass1
{
public int val;
public static AddClass1 operator +(AddClass op1, AddClass op2)
{
AddClass1 returnVal = new AddClass1();
returnVal.val = op1.val + op2.val;
return returnVal;
}
}
种类 | 具体 |
---|---|
一元运算符 | +,-,!,~,++,--,true,false |
二元运算符 | +,-,*,/,%,&,|,^,\<<,>> |
比较运算符 | ==,!=,<,>,<=,=> |
对于==和!=运算符通常需要重写Object.Equals()和Object.GetHashCode()函数,以保证其重载的完整性。
Object.Equals(),以Object对象为参数
说明:Windows 运行时用 C# 或 Visual Basic 编写的类可以重写Equals(Object)方法重载
※Equals()与==的区别:
- 对于值类型来说 两者是相同的 都是比较的变量的值
- 对于引用类型来说,等号(==)比较的是两个变量的”引用”是否一样,即是引用的”地址”是否相同。而对于equals来说仍然比较的是变量的 ”内容” 是否一样
Object.GetHashCode()函数:获取对象实例的一个唯一int值
public override bool Equals(Object op1)
{
if(op1 is AddClass1)
{
return val == ((AddClass1)op1).val;
}
else
{
//操作数类型有误,或者不能转换为正确类型,就会抛出一个异常
throw new ArgumentException("Cannot compare AddClass1 objects with objects of type " + op1.GetType().ToString());
}
}
public override int GetHashCode() => val;
(1)IComparable和IComparer接口是.NET Framework中比较对象的标准方式。
(2)两者的区别:
* IComparable在要比较的对象类中实现,可以比较该对象和另一个对象。
* IComparer在一个单独的类中实现,可以比较任意两个对象
(3)一般使用IComparable给出默认的比较代码,使用其他类给出非默认的比较代码。
(4)IComparable提供了一个方法ComparaTo(),接受对象,返回比较结果【int值】。
(5)IComparer提供方法Compare()。接受两个对象,返回一个整型结果。
string s = "12346";
string m = "2356";
Console.WriteLine($"{Comparer.Default.Compare(s,m)}");
ArrayList包含Sort()方法
//Person.cs
Class Person : IComparable
Field string Name
Field int Age
Method public Person(string name, int age) //构造函数
Method int CompareTo(Object obj)//接口中的比较函数,返回年龄差距
//PersonComparerName.cs
Class PersonComparerName : IComparer
Method public static IComparer Default = new PersonComparerName;
Method public int Compare(object x,object y)
//Program.cs
ArrayList list = new ArrayList();
list.Add(new Person("Rual",30);
...
list.Sort();//两种排序方式
list.Sort(PersonComparerName.Default);
以上代码中两种排序,
第一种调用默认的排序,即CompareTo()函数,可以根据自己的需求改变即CompareTo()函数;
第二种则不然,有公共的静态字段,方便使用,具体Compare(object x,object y)函数如下:
public int Compare(object x,object y)
{
if(x is Person && y is Person)
return Comparer.Default.Compare(((Person)x).Name, ((Person)y).Name);
else
throw new ArgumentException("一个或者两个都不是Person对象。");
}
单词 | 释义 |
---|---|
class | 类 |
struct | 结构 |
property | 属性 |
method | 方法 |
fields | 字段 |