.NET开发基础:从简单的例子理解泛型 分享(2)


/// <summary>
/// 男演员:实现IComparable接口
/// </summary>
public class Boy : IComparable
{
    //姓名
    private string mName;
    //身高
    private int mHeight;
    public string Name {
        get { return this.mName; }
    }
    public int Height {
        get { return this.mHeight; }
    }

public Boy(string name, int height) {
        this.mName = name;
        this.mHeight = height;
    }

public int CompareTo(object obj)
    {
        //比较身高
        return this.mHeight - ((Boy)obj).Height;
    }
}

/// <summary>
/// 女演员:实现IComparable接口
/// </summary>
public class Girl : IComparable
{
    //姓名
    private string mName;
    //体重
    private int mWeight;
    public string Name
    {
        get { return this.mName; }
    }
    public int Weight
    {
        get { return this.mWeight; }
    }

public Girl(string name, int weight){
        this.mName = name;
        this.mWeight = weight;
    }

public int CompareTo(object obj)
    {
        //比较体重
        return ((Girl)obj).Weight - this.mWeight;
    }
}
 


首先让实体类支持自定义的比较,男演员比较身高,女演员比较体重。自定义比较是通过实现IComparable接口完成的,在C#里但凡可以比较的类型,比如int、double、char等都实现了IComparable接口。关于IComparable接口此处不作详述,请读者自行查阅相关资料。
 

复制代码 代码如下:


public class Compare
{
    //万物皆object
    public object WhoIsBetter(object obj1, object obj2)
    {
        object result = obj2;
        //判断比较类型必须相同
        if (obj1.GetType() == obj2.GetType())
        {
            switch (obj1.GetType().ToString())
            {
                //男演员选拔
                case "Generic.Boy":
                    if (((Boy)obj1).CompareTo(obj2) > 0)
                    {
                        result = obj1;
                    }
                    break;
                //女演员选拔
                case "Generic.Girl":
                    if (((Girl)obj1).CompareTo(obj2) > 0)
                    {
                        result = obj1;
                    }
                    break;
                //扩展int类型比较
                case "System.Int32":
                    if (((System.Int32)obj1).CompareTo(obj2) > 0)
                    {
                        result = obj1;
                    }
                    break;
                }
            }
            return result;
        }
    }
 


修改WhoIsBetter方法,除了支持对男演员、女演员的比较,为了展示其扩展性,还新增了int类型的比较。
 

复制代码 代码如下:


//测试
static void Main(string[] args)
{
     Boy boy1 = new Boy("潘长江", 165);
     Boy boy2 = new Boy("刘德华", 175);

Girl girl1 = new Girl("巩俐", 120);
     Girl girl2 = new Girl("周迅", 80);

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjgjfz.html