C # overload operator = and! =

I'm having trouble getting the desired behavior from these several classes and interfaces.

Here is my problem

//Inside a Unit Test that has access to internal methods and properties

INode  firstNode, secondNode;

INodeId  id = new NodeId (4);

first = new Node (id, "node");
second = new Node (id, "node");

Assert.IsTrue (first == second);

The statement above fails because it seems that the class method of the object is equal to the method instead of the overloaded operator in the Node and NodeId classes.

If you have any suggestions on how I can get the desired behavior, this will be awesome.

Here is the part of the Framework I'm working on:

public interface IIdentifier<T> where T : class
{
    TKeyDataType GetKey<TKeyDataType> ();

    bool Equals (IIdentifier<T> obj;
}

public interface INode
{
    string name
    {
        get;
    }

    INodeId id
    {
        get;
    }
}

public interface INodeId : IIdentifier<INode>
{
}

public class Node : INode
{
    internal Node(INodeId  id, string name)
    { 
       //Work
    }

    public static bool operator == (Node n1, Node n2)
    {
        return n1.equals(n2);
    }

    public static bool operator != (Node n1, Node n2)
    {
        return !n1.equals(n2);
    }

    public bool Equals (INode  node)
    {
        return this.name == node.name &&
               this.id = node.id;
    }

    #region INode Properties

    }

public class NodeId : INodeId
{

    internal NodeId(int id)
    { 
       //Work
    }

    public static bool operator == (NodeId  n1, NodeId  n2)
    {
        return n1.equals(n2);
    }

    public static bool operator != (NodeId  n1, NodeId  n2)
    {
        return !n1.equals(n2);
    }

    public override bool Equals (object obj)
    {
        return this.Equals ((IIdentifier<INode>) obj);
    }

    public bool Equals (IIdentifier<INode> obj)
    {
        return obj.GetKey<int>() ==  this.GetKey<int>();
    }

    public TKeyDataType GetKey<TKeyDataType> ()
    {
        return (TKeyDataType) Convert.ChangeType (
            m_id,
            typeof (TKeyDataType),
            CultureInfo.InvariantCulture);
    }


    private int m_id;

}
+3
source share
4 answers

, . , . , , INode.operator==, Node.operator==. INode.operator== , Object.operator==, .

. , Equals(), == - . , operator == , , Equals. , , , .

+6

, Equals (object) Node, NodeId. :

public override bool Equals (object obj)
{
    if (obj is Node)
    {
        return this.Equals(obj as Node);
    }
    return false;
}

// your code (modified to take a Node instead of an INode)
public bool Equals (Node  node)
{
    return this.name == node.name &&
           this.id = node.id;
}
+1

== from, firstNode secondNode Node, INode. .

, , INode.

0

.Equals can be evil if not done right.

Here are the best recommendations for this:

http://msdn.microsoft.com/en-us/library/ms173147(VS.80).aspx

-1
source

Source: https://habr.com/ru/post/1731078/


All Articles