Пожалуйста, помогите мне решить следующую проблему: Прежде всего, у меня есть один класс
namespace ProbA
{
public class A : IComparer
{
Private int a;
public int IComparer.Compare(object CurrentNode, object DataNode)
{
WBPMember Current = (WBPMember)CurrentNode;
WBPMember Data = (WBPMember)DataNode;
return Current.a- Data.a;
}
}
}
namespace BST
{
public class BinarySearchTree<T> : ICollection<T>, IEnumerable<T>
{
public virtual void Add(T data)
{
// create a new Node instance
BinaryTreeNode<T> n = new BinaryTreeNode<T>(data);
int result;
BinaryTreeNode<T> current = root, parent = null;
while (current != null)
{
result = /**** I need to call the Class A compare method.
}
}
}
}
Я хочу выполнить метод ClassA Compare, когда следующий оператор выполняется в сборке ProbA.
A objA = new A();
BinarySearchTree<A> bst = new BinarySearchTree<A>();
Bst.Add(objA);
Проблема в том, что оба класса находятся в разных библиотеках.А BinarySearchTree - это универсальный класс.Итак, как я могу сравнить типизированный объект в функции Add класса BinarySearchTree.
Я обновляю этот пост для получения дополнительных разъяснений.Позвольте мне описать мою проблему более четко.У меня есть какой-то тип businessrules.И в соответствии с различными бизнес-правилами, мне нужно построить другой тип BST.Вне зависимости, BST генерирует ту же логику, но другую логику сравнения.
Допустим, у меня есть сборка BusineesRules.И он содержит 4 вида правил, таких как Business1, Business2, Business3.Бизнес4.И у меня есть сборка для генерации BST и других методов обхода.Этот BST полностью универсален и находится в сборке BST Теперь, когда мне нужно реализовать метод сравнения в каждом классе.Например,
Public Class Business1: IComparer
{
// Implemetation of Icompare.
}
То же самое для всех других классов.
Когда я пытаюсь добавить экземпляр Business1 в BST, сделайте сравнение на основе его собственной реализации и то же самое для других классов.
Код для BST приведен ниже:
public class BinarySearchTree<T> : ICollection<T>, IEnumerable<T>
{
#region "Private Member Variables"
private BinaryTreeNode<T> root = null;
private int count = 0;
private IComparer<T> comparer = Comparer<T>.Default; // used to compare node values when percolating down the tree
#endregion
#region Constructors
public BinarySearchTree() { }
public BinarySearchTree(IComparer<T> comparer)
{
this.comparer = comparer;
}
#endregion
public virtual void Add(T data)
{
// create a new Node instance
BinaryTreeNode<T> n = new BinaryTreeNode<T>(data);
int result;
// now, insert n into the tree
// trace down the tree until we hit a NULL
BinaryTreeNode<T> current = root, parent = null;
while (current != null)
{
result = comparer.Compare(current.Value, data);
if (result == 0)
// they are equal - attempting to enter a duplicate - do nothing
return;
else if (result > 0)
{
// current.Value > data, must add n to current's left subtree
parent = current;
current = current.Left;
}
else if (result < 0)
{
// current.Value < data, must add n to current's right subtree
parent = current;
current = current.Right;
}
}
// We're ready to add the node!
count++;
if (parent == null)
// the tree was empty, make n the root
root = n;
else
{
result = comparer.Compare(parent.Value, data);
if (result > 0)
// parent.Value > data, therefore n must be added to the left subtree
parent.Left = n;
else
// parent.Value < data, therefore n must be added to the right subtree
parent.Right = n;
}
}
#endregion
** Добавить общий метод сравнения.Этот следующий класс добавляется в сборку классов businessrule.
class BusinessRules: IComparer
{
public int Compare(object CurrentHNode, object DataNode)
{
TreeMember Current;
TreeMember Data;
if (CurrentHNode is Current)
{
Current = (TreeMember)CurrentHNode;
}
else
throw new ArgumentException("Object is not type of WBPMember");
if (DataNode is Data)
{
Data = (TreeMember)DataNode;
}
else
throw new ArgumentException("Object is not type of WBPMember");
return Current.TreeIndex - Data.TreeIndex;
}
}
Вы можете увидеть следующую строку в коде.«Result = comparer.Compare (current.Value, data);» Но это сравнение класса двоичного поиска.Поэтому я могу вызвать метод сравнения business1 или business2.Полезна ли эта реализация компаратора для сравнения объектов в методе BinarySearchTree.Add ()?Еще одна важная вещь заключается в том, что BST и другие классы businessrule - это разные сборки.