Effective C# 笔记01

Effective C# 笔记01

第一章使用泛型

IComparable 和IEquatable 接口
在C# 1.0中的非泛型方法和参数,需要修改为泛型方法和参数
其中可以利用C# 2.0 中新定义的系统泛型接口类型

C#2.0 IEquatable<T> 接口

使用方法

public interface IEQuatable<T>
{
    bool Equals(T other)
}

IComparer<T>接口 int Compare(T x, T y);

public int Compare(object x, object y)
        {
            Student s1 = x as Student;
            Student s2 = y as Student;
            return s1.Name.CompareTo(s2.Name);
        }

IComparable<T>接口 int CompareTo(object obj)

public int CompareTo(object obj)
        {
            Student student = obj as Student;
            if (Age > student.Age)
            {
                return 1;
            }
            else if (Age == student.Age)
            {
                return 0;
            }
            else
            {
                return -1;
            }
            //return Age.CompareTo(student.Age);
        }

这个两个接口的参数不一样,

C# 中的泛型类很强大需要多使用

条目2 恰到好处的定义约束

C# 中的约束使用 where T : Type 语法常用的约束类型
class
interface
stract

puclic bool AreEqual<T>(T left,T right)
where T:IComparable<T>
{
    return left.CompareTo(right)==0
}

上面的代码展示了T 类型的约束为继承了IComparable 的类型

猜你喜欢

转载自www.cnblogs.com/clar/p/11220908.html