Effective C # notes 01

Effective C # notes 01

Chapter use generics

IComparable And IEquatable Interface
non-generic methods and parameters in C # 1.0, and the need to modify the parameters for the generic method
which can be used in C # 2.0 newly defined type generic interface system

C # 2.0 IEquatable <T> Interface

Instructions

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);
        }

The parameters of the two interfaces are not the same,

C # generics class is very strong need for multi-use

2 constraint right entry definition

C # uses constraint where T: Type of common syntax constraint type
class
interface
stract

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

The code above shows the types of constraints for the T inherited IComparable type

Guess you like

Origin www.cnblogs.com/clar/p/11220908.html