美文网首页
C#比较器

C#比较器

作者: 晓龙酱 | 来源:发表于2017-09-18 10:32 被阅读27次

    C#类中显示与隐匿转换操作符同时只能实现一个

    // 显示转换操作符
    static public explicit operator Salary(int n)
    {
        Salary s = new Salary(n);
        return s;
    }
    
    // 隐式转换操作符
    static public implicit operator Salary(int n)
    {
            Salary s = new Salary(n);
            return s;
    }
    
    Salary s1 = 100;                // 隐匿转换
    Salary s2 = (Salary)100;        //显示转换
    

    // 实现可比较接口
    using System;
    class Salary : <font color=blue>IComparable<Salary></font>{

    public Salary(int val){
        this.val = val;
    }
    
    public int val
    {
        set;
        get;
    }
    
    override public string ToString()
    {
        return val.ToString();
    }
    <font color=blue>
    public int CompareTo(Salary salary)
    {
        return this.val.CompareTo(salary.val);
    } </font>
    

    }

    
    

    // 实现比较器
    using System.Collections.Generic;
    class SalaryComparer : <font color=blue>IComparer<Salary></font>
    {
    <font color=blue>
    public int Compare(Salary a, Salary b)
    {
    return a.CompareTo(b);
    }</font>
    }

    
    

    List<Salary> ls = new List<Salary>();
    ls.Add(new Salary(3));
    ls.Add(new Salary(2));
    ls.Add(new Salary(1));

    ls.Sort(<font color=blue>new SalaryComparer()</font>);

    foreach(Salary s in ls)
    {
    Debug.Log(s); // 1 2 3
    }

    相关文章

      网友评论

          本文标题:C#比较器

          本文链接:https://www.haomeiwen.com/subject/xxivsxtx.html