使用适配器模式实现两个类对象进行比较大小

1.使用IComparer接口来作为第三方的比较方法

using System;
using System.Collections;

class Employ
{
    public int Age;
    public string Name;

    public Employ(int age, string name)
    {
        Age = age;
        Name = name;
    }
}

class compa : IComparer
{
    public int Compare(object x, object y)
    {
        if (x.GetType() != typeof (Employ) || y.GetType() != typeof (Employ))
            return -1;

        Employ e1 = (Employ) x;
        Employ e2 = (Employ) y;
        if (e1.Age > e2.Age)
            return 1;
        else
        {
            return 0;
        }

    }
}

public class Test
{
    public static void Main()
    {
        Employ[] E=new Employ[2];
         
        E[0] = new Employ(10,"jia");
        E[1] = new Employ(15, "jia1111");
        
        Array.Sort(E, new compa());

        for(int i=0;i<2;i++)
            Console.WriteLine(((Employ)E[i]).Age);

    }
}

2.使用IComparable接口来实现自身对象就可以和其它对象比较

using UnityEngine;
using System.Collections;
using System;

public class Node : IComparable {

    public float nodeTotalCost;
    public float estimatedCost;
    //             a =       b       + a;
    // estimatedCost = nodeTotalCost + estimatedCost;
    // C             =       S       +      H 
    public bool bObstacle;
    public Node parent;
    public Vector3 position;

    public Node()
    {
        this.estimatedCost = 0.0f;
        this.nodeTotalCost = 1.0f;
        this.bObstacle = false;
        this.parent = null;
    }

    public Node(Vector3 pos)
    {
        this.estimatedCost = 0.0f;
        this.nodeTotalCost = 1.0f;
        this.bObstacle = false;
        this.parent = null;
        this.position = pos;
    }

    public void MarkAsObstacle()
    {
        this.bObstacle = true;
    }

    public int CompareTo(object obj)
    {
        Node node = (Node)obj;

        if (this.estimatedCost < node.estimatedCost)
        {
            return -1;
        }

        if (this.estimatedCost > node.estimatedCost)
        {
            return 1;
        }

        return 0;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值