C#比较器

2017-09-18  本文已影响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
}

上一篇下一篇

猜你喜欢

热点阅读