您的位置:首页 > 其它

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

2016-11-13 12:24 357 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐