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的类型

posted @   晓桦  阅读(195)  评论(0编辑  收藏  举报
编辑推荐:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
点击右上角即可分享
微信分享提示